3 回答
TA贡献1827条经验 获得超8个赞
如果您要循环整个数组,那么根本不要使用slice,只需在进入数组时累积项目,当您遇到元素时,只需推送该数组并创建一个新数组,如下所示:
Array.prototype.split = function (element) {
const arrays = [];
let currentArray = []; // is used to accumulate the sub arrays
for(let item of this) { // for each item of the array
if(item === element) { // if item is the element
arrays.push(currentArray); // add the current accumulated array to arrays
currentArray = []; // and start accumulating a new one
} else { // otherwise
currentArray.push(item); // add the item to the accumulated array
}
}
arrays.push(currentArray); // don't forget the last one
return arrays;
}
注意:此答案使用的正确行为split不是问题所要求的。如果要拆分的元素是原始数组中的第一项、最后一项或相邻项,则结果数组中应该有空数组。'abcbdb'.split('b')应该导致['a', 'c', 'd', '']not ['a', 'c', 'd']。如果您想忽略空数组,请查看上面Jhon 接受的答案。
Array.prototype.split = function (element) {
const arrays = [];
let currentArray = [];
for(let item of this) {
if(item === element) {
arrays.push(currentArray);
currentArray = [];
} else {
currentArray.push(item);
}
}
arrays.push(currentArray);
return arrays;
}
let result = ["haii", "keep", "these in the same array but", "stop here", "then continue", "until you reach", "another", "stop here", "and finally", "stop here", "stop here"].split("stop here");
console.log(result);
TA贡献1995条经验 获得超2个赞
这个答案的灵感来自易卜拉欣马里尔的答案。
Array.prototype.split = function (element) {
const arrays = [];
const length = this.length;
let accumulatedArray = [];
for(let i=0; i<length; i++) {
if( this[i] === element ) {
if( accumulatedArray.length > 0 ) arrays.push(accumulatedArray);
accumulatedArray = [];
} else {
accumulatedArray.push(this[i]);
}
}
if( accumulatedArray.length > 0 ) arrays.push(accumulatedArray);;
return arrays;
}
TA贡献1856条经验 获得超11个赞
在我的例子中,首先.join()你的数组有一个独特的分隔符UNIQUE_SEPERATOR
然后你首先将它拆分.split("stop here"),返回一个包含 3 个字符串的数组。
现在您需要.map()遍历数组并用分隔符 (UNIQUE_SEPERATOR) 将其拆分并.filter()输出""值。
最后,您通过检查其长度来过滤掉空数组,然后就完成了。
let arr = [
"haii",
"keep",
"these in the same array but",
"stop here",
"then continue",
"until you reach",
"another",
"stop here",
"and finally",
"stop here",
"stop here"
];
Array.prototype.split = function() {
return this.join("UNIQUE_SEPERATOR")
.split("stop here")
.map(el => el.split("UNIQUE_SEPERATOR").filter(Boolean))
.filter(arr => arr.length);
};
console.log(arr.split());
添加回答
举报