tag*_*s2k 2709 javascript arrays jquery insert
我正在寻找一种JavaScript数组插入方法,其格式为:
arr.insert(index, item)
Run Code Online (Sandbox Code Playgroud)
最好是在jQuery中,但任何JavaScript实现都会在这一点上完成.
tva*_*son 4382
你想要的是splice本机数组对象上的函数.
arr.splice(index, 0, item);将插入item到arr指定索引处(删除0第一个项目,也就是说,它只是一个插件).
在这个例子中,我们将创建一个数组并将一个元素添加到索引2中:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());Run Code Online (Sandbox Code Playgroud)
小智 269
您可以Array.insert通过执行以下操作来实现该方法:
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用它:
var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
Run Code Online (Sandbox Code Playgroud)
Gaa*_*far 116
除了拼接之外,您可以使用这种方法,它不会改变原始数组,但会创建一个带有添加项的新数组.你应该尽可能避免变异.我在这里使用ES6传播运营商.
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)
// [1, 10, 2, 3, 4, 5]Run Code Online (Sandbox Code Playgroud)
这可以通过稍微调整函数来添加多个项目以使用其余运算符来处理新项目,并将其传播到返回的结果中
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, ...newItems) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted items
...newItems,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10, 20)
console.log(result)
// [1, 10, 20, 2, 3, 4, 5]Run Code Online (Sandbox Code Playgroud)
Ran*_*ner 90
使用Array.prototype.splice()是实现它的一种优雅的方式
const numbers = ['one', 'two', 'four', 'five']
numbers.splice(2, 0, 'three');
console.log(numbers)Run Code Online (Sandbox Code Playgroud)
阅读有关Array.prototype.splice的更多信息
Vis*_*ioN 74
insert方法/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat(
Array.prototype.slice.call(arguments, 1)));
return this;
};
Run Code Online (Sandbox Code Playgroud)
它可以插入多个元素(如本机splice一样)并支持链接:
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]
Run Code Online (Sandbox Code Playgroud)
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
index = Math.min(index, this.length);
arguments.length > 1
&& this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
&& this.insert.apply(this, arguments);
return this;
};
Run Code Online (Sandbox Code Playgroud)
它可以将参数中的数组与给定数组合并,并且还支持链接:
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/UPphH/
Gas*_*ass 47
splice()它splice()添加元素时该方法通常接收三个参数:
0let array = ['item 1', 'item 2', 'item 3']
let insertAtIndex = 0
let itemsToRemove = 0
array.splice(insertAtIndex, itemsToRemove, 'insert this string at index 0')
console.log(array)Run Code Online (Sandbox Code Playgroud)
Lui*_*rez 36
如果要一次将多个元素插入到数组中,请查看此Stack Overflow答案:在javascript中将数组拼接成数组的更好方法
这里还有一些函数来说明这两个例子:
function insertAt(array, index) {
var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
return insertArrayAt(array, index, arrayToInsert);
}
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
return array;
}
Run Code Online (Sandbox Code Playgroud)
最后这里有一个jsFiddle所以你可以自己看看:http://jsfiddle.net/luisperezphd/Wc8aS/
这就是你如何使用这些功能:
// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");
// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);
Run Code Online (Sandbox Code Playgroud)
Red*_*edu 21
为了正确的功能编程和链接目的,发明Array.prototype.insert()是必不可少的.实际上,如果它已经返回变异数组而不是一个完全没有意义的空数组,则splice可能是完美的.所以这就是它
Array.prototype.insert = function(i,...rest){
this.splice(i,0,...rest)
return this
}
var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");Run Code Online (Sandbox Code Playgroud)
好吧,上面的Array.prototype.splice()一个变异原始数组,有些人可能会抱怨"你不应该修改不属于你的东西",这可能也是正确的.所以对于公益事业,我想给另一个Array.prototype.insert()不改变原始阵列的公益事业.在这里;
Array.prototype.insert = function(i,...rest){
return this.slice(0,i).concat(rest,this.slice(i));
}
var a = [3,4,8,9],
b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 20
今天(2020.04.24)我对大小阵列的选定解决方案进行了测试。我在 Chrome 81.0、Safari 13.1 和 Firefox 75.0上的macOS v10.13.6 (High Sierra) 上测试了它们。
适用于所有浏览器
slice和reduce(D,E,F) 的非就地解决方案通常比就地解决方案快 10 到 100 倍splice(AI、BI 和 CI)的就地解决方案最快(有时约为 100 倍 - 但取决于阵列大小)测试分为两组:就地解决方案(AI、BI 和 CI)和非就地解决方案(D、E 和 F),并针对两种情况执行:
测试代码显示在以下代码段中:
function AI(arr, i, el) {
arr.splice(i, 0, el);
return arr;
}
function BI(arr, i, el) {
Array.prototype.splice.apply(arr, [i, 0, el]);
return arr;
}
function CI(arr, i, el) {
Array.prototype.splice.call(arr, i, 0, el);
return arr;
}
function D(arr, i, el) {
return arr.slice(0, i).concat(el, arr.slice(i));
}
function E(arr, i, el) {
return [...arr.slice(0, i), el, ...arr.slice(i)]
}
function F(arr, i, el) {
return arr.reduce((s, a, j)=> (j-i ? s.push(a) : s.push(el, a), s), []);
}
// -------------
// TEST
// -------------
let arr = ["a", "b", "c", "d", "e", "f"];
let log = (n, f) => {
let a = f([...arr], 3, "NEW");
console.log(`${n}: [${a}]`);
};
log('AI', AI);
log('BI', BI);
log('CI', CI);
log('D', D);
log('E', E);
log('F', F);Run Code Online (Sandbox Code Playgroud)
This snippet only presents tested code (it not perform tests)Run Code Online (Sandbox Code Playgroud)
Google Chrome 上小数组的示例结果如下:
Ali*_*eza 15
我建议在这种情况下使用纯JavaScript,在JavaScript中也没有插入方法,但我们有一个方法,它是一个 内置的Array方法,它为你完成工作,它被称为splice ...
让我们看看什么是splice() ......
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容.
好吧,想象一下我们在下面有这个数组:
const arr = [1, 2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)
我们可以这样删除3:
arr.splice(arr.indexOf(3), 1);
Run Code Online (Sandbox Code Playgroud)
它将返回3,但如果我们现在检查arr,我们有:
[1, 2, 4, 5]
Run Code Online (Sandbox Code Playgroud)
到目前为止,这么好,但我们如何使用splice向阵列添加新元素?让我们回到3 ...
arr.splice(2, 0, 3);
Run Code Online (Sandbox Code Playgroud)
让我们看看我们做了什么......
我们再次使用拼接,但是这次为第二个参数,我们传递0,意味着我们想要删除没有项目,但同时,我们添加第三个参数,即将在第二个索引添加的3个...
您应该知道,我们可以同时删除和添加,例如现在我们可以这样做:
arr.splice(2, 2, 3);
Run Code Online (Sandbox Code Playgroud)
这将删除索引2处的2个项目,然后在索引2处添加3,结果将为:
[1, 2, 3, 5];
Run Code Online (Sandbox Code Playgroud)
这显示了拼接中的每个项目如何工作:
array.splice(start,deleteCount,item1,item2,item3 ......)
M. *_*put 13
这里有两种方法:
const array = [ 'My', 'name', 'Hamza' ];
array.splice(2, 0, 'is');
console.log("Method 1: ", array.join(" "));Run Code Online (Sandbox Code Playgroud)
或者
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
const array = [ 'My', 'name', 'Hamza' ];
array.insert(2, 'is');
console.log("Method 2 : ", array.join(" "));Run Code Online (Sandbox Code Playgroud)
vka*_*v15 12
Array#splice()是要走的路,除非你真的想避免改变数组。给定 2 个数组arr1and arr2,以下是将内容插入arr2到arr1第一个元素之后的方法:
const arr1 = ['a', 'd', 'e'];
const arr2 = ['b', 'c'];
arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']
console.log(arr1)Run Code Online (Sandbox Code Playgroud)
如果您担心变异的阵列(例如,如果使用Immutable.js),您可以改用slice(),不要与混淆splice()了'p'。
const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];
Run Code Online (Sandbox Code Playgroud)
Sri*_*hna 10
在特定索引处附加单个元素
//Append at specific position(here at index 1)
arrName.splice(1, 0,'newName1');
//1: index number, 0: number of element to remove, newName1: new element
//Append at specific position (here at index 3)
arrName[3] = 'newName1';
Run Code Online (Sandbox Code Playgroud)
在特定索引处附加多个元素
//Append from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
//1: index number from where append start,
//0: number of element to remove,
//newElemenet1,2,3: new elements
Run Code Online (Sandbox Code Playgroud)
任何人仍然遇到这个问题并且在以前的答案中尝试了所有选项但从未得到它的人。我正在分享我的解决方案,这是考虑到您不想明确说明对象与数组的属性。
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj))
count++;
});
return count > 0;
}
Run Code Online (Sandbox Code Playgroud)
这是迭代引用数组并将其与您要检查的对象进行比较,将它们都转换为字符串,然后迭代是否匹配的组合。然后你就可以数数了。这可以改进,但这是我解决的地方。
splice如果您需要就地插入数组,使用该方法肯定是最好的答案。
但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时改变原始数组,则可以使用以下函数。
function insert(array, index) {
const items = Array.prototype.slice.call(arguments, 2);
return [].concat(array.slice(0, index), items, array.slice(index));
}
const list = ['one', 'two', 'three'];
const list1 = insert(list, 0, 'zero'); // Insert single item
const list2 = insert(list, 3, 'four', 'five', 'six'); // Insert multiple
console.log('Original list: ', list);
console.log('Inserted list1: ', list1);
console.log('Inserted list2: ', list2);Run Code Online (Sandbox Code Playgroud)
注意:这是ES6 之前的一种方式,因此它适用于旧浏览器和新浏览器。
如果您使用的是 ES6,那么您也可以尝试使用rest 参数;看到这个答案。
我试过这个,它工作正常!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
Run Code Online (Sandbox Code Playgroud)
索引是您要插入或删除元素的位置。
0,即第二个参数,定义要从索引中删除的元素数。
item包含要在数组中创建的新条目。它可以是一个或多个。
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
Run Code Online (Sandbox Code Playgroud)
另一个可能的解决方案,使用Array#reduce.
var arr = ["apple", "orange", "raspberry"],
arr2 = [1, 2, 4];
function insert(arr, item, index) {
arr = arr.reduce(function(s, a, i) {
i == index ? s.push(item, a) : s.push(a);
return s;
}, []);
console.log(arr);
}
insert(arr, "banana", 1);
insert(arr2, 3, 2);Run Code Online (Sandbox Code Playgroud)
获利的reduce方法如下:
function insert(arr, val, index) {
return index >= arr.length
? arr.concat(val)
: arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}
Run Code Online (Sandbox Code Playgroud)
因此,通过这种方式,我们可以返回一个新数组(将是一种很酷的函数方式 - 比使用push或splice好得多),其中元素插入在索引处,如果索引大于数组的长度,它将被插入在末尾。
你可以用 array.splice 来做到这一点:
/**
* @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);;
}
Run Code Online (Sandbox Code Playgroud)
即使已经回答了这个问题,我还是将这个说明添加到另一种方法中.
我想一个放置已知数量的项的成阵列,进入特定位置,因为它们脱落,其通过定义不保证在排序顺序的"关联数组"(即对象)的.我希望生成的数组是一个对象数组,但是由于数组保证了它们的顺序,所以对象在数组中按特定的顺序排列.所以我这样做了.
首先是源对象,从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);
Run Code Online (Sandbox Code Playgroud)
由于对象中的节点数是已知的,我首先创建一个具有指定长度的数组:
var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);
Run Code Online (Sandbox Code Playgroud)
然后迭代对象,将新创建的临时对象放入数组中的所需位置,而不进行任何"排序".
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);
Run Code Online (Sandbox Code Playgroud)
这是我在我的一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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("");
};
Run Code Online (Sandbox Code Playgroud)
然后我在下面称它为。
ifExist("friends", [ ' ( ', ' )' ], 1)} // Output: ( friends )
ifExist("friends", [ ' - '], 1)} // Output: - friends
ifExist("friends", [ ':'], 0)} // Output: friends:
Run Code Online (Sandbox Code Playgroud)
我不得不同意 Redu 的回答,因为 splice() 肯定有一些令人困惑的界面。cdbajorin 给出的响应“它仅在第二个参数为 0 时返回一个空数组。如果它大于 0,则返回从数组中删除的项目”,虽然准确,但证明了这一点。
该函数的目的是拼接,或者正如 Jakob Keller 之前所说的,“加入或连接,也改变。
你有一个既定的数组,你现在正在改变它会涉及添加或删除元素......”鉴于此,被删除的元素的返回值(如果有的话)充其量是尴尬的。我 100% 同意这一点方法可能更适合链接,如果它返回了看起来很自然的东西,一个添加了拼接元素的新数组。然后你可以做这样的事情 ["19", "17"].splice(1,0,"18" ).join("...") 或任何你喜欢的返回数组。
它返回已删除内容的事实只是一种无稽之谈,恕我直言。如果该方法的目的是“剪出一组元素”,那可能是它的唯一目的。似乎如果我不知道我已经剪掉了什么,我可能没有理由剪掉这些元素,不是吗?
如果它的行为类似于 concat()、map()、reduce()、slice() 等,其中一个新数组是由现有数组组成的,而不是改变现有数组,那就更好了。这些都是可链接的,这是一个重要的问题。链式数组操作相当常见。
语言似乎需要朝着一个或另一个方向发展,并尽可能地坚持下去。JavaScript 是功能性的且声明性较少,这似乎是对规范的奇怪偏离。
我喜欢一点安全性,我用这个:
Array.prototype.Insert = function (item, before) {
if (!item) return;
if (before == null || before < 0 || before > this.length - 1) {
this.push(item);
return;
}
this.splice(before, 0, item);
}
var t = ["a", "b"]
t.Insert("v", 1)
console.log(t)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1711160 次 |
| 最近记录: |