|
| 1 | +function WString() { |
| 2 | + this.value = []; // 初始化 wString对象 时,里面定义 一个空数组,将来用来装数据的容器 |
| 3 | + this.length = 0; //因为是空数组,所以现在的长度是0 |
| 4 | + /** |
| 5 | + * push()方法用于在数组的末端添加 数组的元素,并返回添加新元素后的数组长度。 |
| 6 | + * 如果入参不合法,将会抛错; |
| 7 | + * 如果运行出错,将会返回空数组。 |
| 8 | + * @param {...any} item1 |
| 9 | + * @returns |
| 10 | + */ |
| 11 | + this.push = function (...item1) { // 当传入多个参数入来时 可用 ...形参名 表示 |
| 12 | + |
| 13 | + if (item1 == undefined || item1 == null || item1.length == 0) { |
| 14 | + throw new error('入参不合法'); |
| 15 | + } |
| 16 | + try { |
| 17 | + for (let i = this.value.length, j = 0; j < item1.length; i++, j++) { |
| 18 | + this.value[i] = item1[j] |
| 19 | + } |
| 20 | + this.length += item1.length; |
| 21 | + return this.length; |
| 22 | + |
| 23 | + } catch (error) { |
| 24 | + console.log(error) |
| 25 | + } |
| 26 | + }; |
| 27 | + |
| 28 | + /** |
| 29 | + * charAt() 方法返回指定位置的字符,参数是从0开始编号的位置。 |
| 30 | + * @param {*} item |
| 31 | + * @returns |
| 32 | + */ |
| 33 | + this.chartAt = function (item) { |
| 34 | + if (item == undefined || item == null || item > this.value.length || item < 0) { |
| 35 | + return this.value[0]; |
| 36 | + } |
| 37 | + try { |
| 38 | + for (let i = 0; i < this.value.length; i++) { |
| 39 | + if (i === item) { |
| 40 | + return this.value[i]; |
| 41 | + } |
| 42 | + } |
| 43 | + } catch (error) { |
| 44 | + console.log(error) |
| 45 | + } |
| 46 | + |
| 47 | + }; |
| 48 | + /** |
| 49 | + * concat() 方法用于 连接 两个字符串,返回一个新字符串,不改变原字符串 |
| 50 | + * 如果参数不是字符串,concat() 方法会将其转为字符串,然后再连接 |
| 51 | + * @param {...any} concatStr |
| 52 | + * @returns |
| 53 | + */ |
| 54 | + this.concat = function (...concatStr) { |
| 55 | + if (concatStr == undefined) { |
| 56 | + concatStr = undefined |
| 57 | + } |
| 58 | + if (concatStr == null) { |
| 59 | + concatStr = null |
| 60 | + } |
| 61 | + try { |
| 62 | + let concatVal = this.value; |
| 63 | + for (let i = 0; i < concatStr.length; i++) { |
| 64 | + concatVal.push(concatStr[i]); |
| 65 | + }; |
| 66 | + let val = concatVal.toString(); |
| 67 | + let result = ''; |
| 68 | + for (let j = 0; j < val.length; j++) { |
| 69 | + if (',' != val[j]) { |
| 70 | + result += val[j] |
| 71 | + }; |
| 72 | + }; |
| 73 | + return result; |
| 74 | + } catch (error) { |
| 75 | + console.log(error); |
| 76 | + } |
| 77 | + |
| 78 | + }; |
| 79 | + |
| 80 | +} |
| 81 | + |
| 82 | +let wString = new WString(); |
| 83 | +wString.push('A', 'B', 'C', 'D'); |
| 84 | +console.log('before: ', wString) |
| 85 | + |
| 86 | +let charAtString = wString.chartAt(3); |
| 87 | +console.log('charAtString = ', charAtString); |
| 88 | + |
| 89 | +let concatValueof = wString.concat('e', 'f', 1, undefined, null, 3, 0); |
| 90 | +console.log(' concatValueof = ', concatValueof) |
| 91 | + |
0 commit comments