我正在寻找一个JavaScript数组插入方法,样式如下:

arr.insert(index, item)

最好是在jQuery中,但此时任何JavaScript实现都可以。


当前回答

尽管这个问题已经得到了回答,但我还是添加了这个注释作为替代方法。

我想将已知数量的项目放入一个数组中,放入特定位置,因为它们来自一个“关联数组”(即一个对象),根据定义,该数组不能保证按排序顺序排列。我希望得到的数组是一个对象数组,但是对象在数组中的顺序是特定的,因为数组保证了它们的顺序。所以我这样做了。

首先是源对象,一个从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);

其他回答

在这种情况下,我建议使用纯JavaScript。JavaScript中也没有任何insert方法,但我们有一个内置Array方法,它为您完成任务。这叫做拼接。。。

让我们看看什么是拼接()。。。

splice()方法通过删除现有元素和/或添加新元素。

好的,假设我们有下面这个数组:

const arr = [1, 2, 3, 4, 5];

我们可以这样删除3个:

arr.splice(arr.indexOf(3), 1);

它将返回3,但如果我们现在检查arr,我们有:

[1, 2, 4, 5]

到目前为止,还不错,但我们如何使用拼接将新元素添加到数组中?

让我们把三个放回。。。

arr.splice(2, 0, 3);

让我们看看我们做了什么。。。

我们再次使用拼接,但这次对于第二个参数,我们传递了0,这意味着我们不想删除任何项,但同时,我们添加了第三个参数,即将在第二个索引中添加的3。。。

您应该知道,我们可以同时删除和添加。例如,现在我们可以做到:

arr.splice(2, 2, 3);

这将删除索引2中的两个项目。然后在索引2处添加3,结果将是:

[1, 2, 3, 5];

这显示了拼接中的每个项目是如何工作的:

array.拼接(开始,删除计数,项目1,项目2,项目3…)

通过执行以下操作,可以实现Array.insert方法:

Array.prototype.insert = function ( index, ...items ) {
    this.splice( index, 0, ...items );
};

然后你可以像这样使用它:

var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

任何对这个问题仍有疑问的人,都尝试过前面答案中的所有选项,但都没有得到。我分享我的解决方案,这是为了考虑到您不想显式地声明对象与数组的财产。

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;
}

这是对引用数组进行迭代并将其与要检查的对象进行比较的组合,将两者转换为字符串,然后在匹配时进行迭代。然后你就可以数了。这是可以改进的,但这是我解决的问题。

这是我在一个应用程序中使用的一个工作函数。

这将检查项目是否存在:

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);; 
}

阵列切片的文档