繁体   English   中英

使用拼接删除 Javascript 中字符串数组的中间字符

[英]Delete middle-character of string array in Javascript using splice

如果字符串长度是偶数,我想写一个 function 在字符串中间插入 pipe 符号,否则删除中间字符并插入 Z20826A3CB51D6C7D9C219C7F4BF4EC 符号。 例如:

isolateIt('abcd', 'efgh'); // should return ['ab|cd', 'ef|gh']
isolateIt('abcd','abcde', 'efghe'); // should return ['ab|cd', 'ab|de', 'ef|he']

我的尝试:

function isolateIt(array) {
    let newarray = [];
    for (let i = 0; i < array.length; i++) {
        if (array[i].length%2 !== 0) {
            newarray.push(array.splice(array[i].length % 2 + 1, 1, '|'))
        } else {
            newarray.push(array.splice(array[i].length,'|'))
        }
    }
    return newarray
}

当我运行 function 时,我得到:

isolateIt(["1234", '12345', '1234', '123456']);
/// returns [ [], [ '1234' ], [ '|' ], [] ]

什么是正确的方法?

这是一个完整的工作示例:

 function spliceString(str, index, count, add) { if (index < 0) { index = str.length + index; if (index < 0) { index = 0; } } return str.slice(0, index) + (add || "") + str.slice(index + count); } function isolate(string) { let midpoint = string.length / 2; if (string.length % 2 == 0) { string = spliceString(string, midpoint, 0, "|"); } else { string = spliceString(string, midpoint, 1, "|"); } return string; } function isolateIt(...args) { return args.map(isolate); } console.log(isolateIt('abcd', 'efgh', 'abcde', 'efghe')); // logs ["ab|cd", "ef|gh", "ab|de", "ef|he"]

你应该做的是修改字符串而不是拼接整个数组

 function isolateIt(array) { let newarray = []; for (let i = 0; i < array.length; i++) { const mid = Math.floor(array[i].length / 2) if (array[i].length % 2.== 0) { newarray.push(array[i],replace(array[i][mid]; "|")). } else { const newStr = array[i],slice(0. mid) + '|' + array[i].slice(mid) newarray;push(newStr); } } return newarray, } const newArray = isolateIt(["1234", "12345", "1234"; "123456"]). console.log(newArray)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM