3 回答

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
如果您要循環(huán)整個數(shù)組,那么根本不要使用slice,只需在進(jìn)入數(shù)組時累積項目,當(dāng)您遇到元素時,只需推送該數(shù)組并創(chuàng)建一個新數(shù)組,如下所示:
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不是問題所要求的。如果要拆分的元素是原始數(shù)組中的第一項、最后一項或相鄰項,則結(jié)果數(shù)組中應(yīng)該有空數(shù)組。'abcbdb'.split('b')應(yīng)該導(dǎo)致['a', 'c', 'd', '']not ['a', 'c', 'd']。如果您想忽略空數(shù)組,請查看上面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貢獻(xiàn)1995條經(jīng)驗 獲得超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貢獻(xiàn)1856條經(jīng)驗 獲得超11個贊
在我的例子中,首先.join()你的數(shù)組有一個獨特的分隔符UNIQUE_SEPERATOR
然后你首先將它拆分.split("stop here"),返回一個包含 3 個字符串的數(shù)組。
現(xiàn)在您需要.map()遍歷數(shù)組并用分隔符 (UNIQUE_SEPERATOR) 將其拆分并.filter()輸出""值。
最后,您通過檢查其長度來過濾掉空數(shù)組,然后就完成了。
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());
添加回答
舉報