我想编写一个函数,如果字符串长度为偶数,则在字符串中间插入管道符号,否则删除中间字符并插入管道符号。例如:
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
}
当我运行函数时,我得到:
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)