我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
let ifExist = (item, strings = [ '' ], position = 0) => {
// Output into an array with an empty string. Important just in case their isn't any item.
let output = [ '' ];
// Check to see if the item that will be positioned exist.
if (item) {
// Output should be equal to an array of strings.
output = strings;
// Use splice() in order to break the array.
// Use positional parameters to state where to put the item
// and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
output.splice(position, 0, item);
}
// Empty string is so we do not concatenate with comma or anything else.
return output.join("");
};
然后我把它叫做下面。
ifExist("friends", [ ' ( ', ' )' ], 1)} // Output: ( friends )
ifExist("friends", [ ' - '], 1)} // Output: - friends
ifExist("friends", [ ':'], 0)} // Output: friends:
其他回答
您可以使用array.spling执行此操作:
/**
* @param arr: Array
* @param item: item to insert
* @param index: index at which to insert
* @returns array with the inserted element
*/
export function _arrayInsertAt<T>(arr: T[], item: T, index: number) {
return arr.splice(index, 0, item);;
}
阵列切片的文档
尽管这个问题已经得到了回答,但我还是添加了这个注释作为替代方法。
我想将已知数量的项目放入一个数组中,放入特定位置,因为它们来自一个“关联数组”(即一个对象),根据定义,该数组不能保证按排序顺序排列。我希望得到的数组是一个对象数组,但是对象在数组中的顺序是特定的,因为数组保证了它们的顺序。所以我这样做了。
首先是源对象,一个从PostgreSQL检索的JSONB字符串。我想让它按每个子对象中的“order”属性排序。
var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';
var jsonb_obj = JSON.parse(jsonb_str);
由于对象中的节点数是已知的,因此我首先创建一个具有指定长度的数组:
var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);
然后迭代对象,将新创建的临时对象放置到数组中所需的位置,而不进行任何“排序”。
for (var key of Object.keys(jsonb_obj)) {
var tobj = {};
tobj[key] = jsonb_obj[key].abbr;
var position = jsonb_obj[key].order - 1;
sorted_array[position] = tobj;
}
console.dir(sorted_array);
以下是现代(字体功能)方式:
export const insertItemInList = <T>(
arr: T[],
index: number,
newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]
除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用ES6排列运算符。
常量项=[1,2,3,4,5]常量插入=(arr,索引,newItem)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10)console.log(结果)// [1, 10, 2, 3, 4, 5]
这可以用于添加多个项目,方法是稍微调整函数,为新项目使用rest运算符,并在返回的结果中传播:
常量项=[1,2,3,4,5]常量插入=(arr,索引,…newItems)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目…新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10,20)console.log(结果)// [1, 10, 20, 2, 3, 4, 5]
我喜欢一点安全,我用这个:
Array.prototype.Insert=函数(项,之前){if(!item)返回;if(before==null|| before<0|| before>this.length-1){this.push(项目);回来}此.拼接(之前,0,项);}var t=[“a”,“b”]t.插入(“v”,1)控制台日志(t)