簡體   English   中英

如何替換數組中的項目?

[英]How to replace item in array?

這個數組的每一項都是一些數字:

var items = Array(523,3452,334,31, ...5346);

如何用新的替換一些項目?

例如,我們想用1010替換3452 ,我們該怎么做呢?

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

此外,建議您不要使用構造函數方法來初始化數組。 相反,使用文字語法:

var items = [523, 3452, 334, 31, 5346];

如果您喜歡簡潔的 JavaScript 並希望縮短-1比較,您也可以使用~運算符:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

有時我什至喜歡編寫一個contains函數來抽象這個檢查,並使其更容易理解發生了什么。 很棒的是,這適用於數組和字符串:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

從用於字符串的 ES6/ES2015 開始,並為用於數組的 ES2016 提議,您可以更輕松地確定源是否包含另一個值:

if (haystack.includes(needle)) {
    // do your thing
}

Array.indexOf()方法將替換第一個實例。 要獲取每個實例,請使用Array.map()

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

當然,這會創建一個新數組。 如果你想就地做,使用Array.forEach()

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

我建議的解決方案是:

items.splice(1, 1, 1010);

拼接操作將刪除 1 個項目,從數組中的位置 1(即3452 )開始,並將其替換為新項目1010

使用indexOf查找元素。

var i = items.indexOf(3452);
items[i] = 1010;

@gilly3 的回答很棒。

替換對象數組中的對象,保持元素的順序不變

當我從服務器獲取數據時,我更喜歡以下方式將新的更新記錄更新到我的記錄數組中。 它使訂單保持完整,並且非常直接地使用一個班輪。

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

 var users = [ {id: 1, firstname: 'John', lastname: 'Ken'}, {id: 2, firstname: 'Robin', lastname: 'Hood'}, {id: 3, firstname: 'William', lastname: 'Cook'} ]; var editedUser = {id: 2, firstname: 'Michael', lastname: 'Angelo'}; users = users.map(u => u.id !== editedUser.id ? u : editedUser); console.log('users -> ', users);

使用for循環輕松完成。

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

第一種方法

在一行中替換或更新數組項的最佳方法

array.splice(array.indexOf(valueToReplace), 1, newValue)

例如:

let items = ['JS', 'PHP', 'RUBY'];

let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')

console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']

第二種方法

執行相同操作的另一種簡單方法是:

items[items.indexOf(oldValue)] = newValue

如果使用復雜的對象(甚至是簡單的對象)並且可以使用 es6,那么Array.prototype.findIndex是一個不錯的選擇。 對於 OP 的陣列,他們可以這樣做,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

對於更復雜的對象,這真的很閃耀。 例如,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

您可以使用索引編輯任意數量的列表

例如 :

items[0] = 5;
items[5] = 100;

ES6方式:

const items = Array(523, 3452, 334, 31, ...5346);

我們想用1010替換3452 ,解決方案:

const newItems = items.map(item => item === 3452 ? 1010 : item);

當然,問題是多年前的問題,現在我更喜歡使用不可變的解決方案,當然,它對ReactJS來說很棒。

對於經常使用,我提供以下功能:

const itemReplacer = (array, oldItem, newItem) =>
  array.map(item => item === oldItem ? newItem : item);

替換可以在一行中完成:

 var items = Array(523, 3452, 334, 31, 5346); items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010 console.log(items);

或者創建一個函數來重用:

 Array.prototype.replace = function(t, v) { if (this.indexOf(t)!= -1) this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v; }; //Check var items = Array(523, 3452, 334, 31, 5346); items.replace(3452, 1010); console.log(items);

使用 ES6 擴展運算符和.slice方法替換列表中元素的不可變方法。

const arr = ['fir', 'next', 'third'], item = 'next'

const nextArr = [
  ...arr.slice(0, arr.indexOf(item)), 
  'second',
  ...arr.slice(arr.indexOf(item) + 1)
]

驗證是否有效

console.log(arr)     // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']

在javascript中替換數組元素的功能方法:

 const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];

最簡單的方法是使用一些庫,如underscorejs和 map 方法。

var items = Array(523,3452,334,31,...5346);

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]
var items = Array(523,3452,334,31,5346);

如果您知道該值,則使用,

items[items.indexOf(334)] = 1010;

如果您想知道該值是否存在,請使用,

var point = items.indexOf(334);

if (point !== -1) {
    items[point] = 1010;
}

如果您知道地點(位置),則直接使用,

items[--position] = 1010;

如果你想替換幾個元素,並且你只知道起始位置意味着,

items.splice(2, 1, 1010, 1220);

有關.splice 的更多信息

好吧,如果有人對如何從數組中的索引替換對象感興趣,這里有一個解決方案。

通過 id 查找對象的索引:

const index = items.map(item => item.id).indexOf(objectId)

使用 Object.assign() 方法替換對象:

Object.assign(items[index], newValue)

如果你想要一個簡單的糖sintax oneliner,你可以:

(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);

喜歡:

let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };

如果您沒有 id,則可以將元素字符串化,例如:

(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);
var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

從這里你可以從數組中刪除一個特定的值,並基於相同的索引你可以在數組中插入值。

 Array.splice(index, 0, Array value);

這是單班輪。 它假設該項目將在數組中。

 var items = [523, 3452, 334, 31, 5346] var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr) console.log(replace(items, 3452, 1010))

首先,像這樣重寫你的數組:

var items = [523,3452,334,31,...5346];

接下來,通過其索引號訪問數組中的元素。 確定索引號的公式為: n-1

要替換數組中的第一項(n=1) ,請編寫:

items[0] = Enter Your New Number;

在您的示例中,數字3452位於第二個位置(n=2) 所以確定索引號的公式是2-1 = 1 因此編寫以下代碼將3452替換為1010

items[1] = 1010;

這是可重用功能的基本答案:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

我使用 for 循環解決了這個問題,並遍歷原始數組並將匹配區域的位置添加到另一個數組,然后循環遍歷該數組並在原始數組中更改它然后返回它,我使用了箭頭函數,但是一個常規函數也會工作。

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};
presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.

最簡單的方法是這個。

var items = Array(523,3452,334,31, 5346);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);

console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]
 items[items.indexOf(3452)] = 1010

非常適合簡單的交換。 試試下面的片段

 const items = Array(523, 3452, 334, 31, 5346); console.log(items) items[items.indexOf(3452)] = 1010 console.log(items)

當您的數組有許多舊項目替換新項目時,您可以使用這種方式:

 function replaceArray(array, oldItem, newItem) { for (let i = 0; i < array.length; i++) { const index = array.indexOf(oldItem); if (~index) { array[index] = newItem; } } return array } console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, 5)); console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, "Hi"));

 const items = Array(1, 2, 3, 4, 5); console.log(items) items[items.indexOf(2)] = 1010 console.log(items)

此數組的每個項目都是一些數字:

var items = Array(523,3452,334,31, ...5346);

如何用新物品代替某些物品?

例如,我們想替換34521010 ,我們會怎么做呢?

此數組的每個項目都是一些數字:

var items = Array(523,3452,334,31, ...5346);

如何用新物品代替某些物品?

例如,我們想替換34521010 ,我們會怎么做呢?

這將完成工作

Array.prototype.replace = function(a, b) {
    return this.map(item => item == a ? b : item)
}

用法:

let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))

Output:

['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']

好消息是,每個數組都將具有.replace()屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM