어레이 내의 아이템을 교환하는 방법
이 어레이의 각 항목은 몇 가지 번호입니다.
var items = Array(523,3452,334,31, ...5346);
새 아이템으로 교체하려면 어떻게 해야 하나요?
를 들어, '어울리다', '어울리다', '어울리다' 이렇게 .3452
1010
떻게게 하면 ?? ???
var index = items.indexOf(3452);
if (index !== -1) {
items[index] = 1010;
}
또한 컨스트럭터 방식을 사용하여 어레이를 초기화하지 않는 것이 좋습니다.대신 리터럴 구문을 사용합니다.
var items = [523, 3452, 334, 31, 5346];
이 경우에도 하실 수 있습니다.~
JavaScript에 연산자의 JavaScript를 하고 싶은 operator.-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; });
@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);
제안 솔루션은 다음과 같습니다.
items.splice(1, 1, 1010);
1에서 1개 항목)을합니다. 1번으로 하다3452
1010
.
indexOf
요소를 찾을 수 있습니다.
var i = items.indexOf(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
for
loopsyslog.syslog..syslog.
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 1010;
오브젝트를할 수 경우, es6를 사용할 수 있습니다.Array.prototype.findIndex
좋은 것 같아요.은 OP 어 、 OP 어 、 OP 어 、 OP の for for for for for for for for for
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);
는 we ★★★★★★★★★★★★★★★★★★★.3452
1010
, 루루:
const newItems = items.map(item => item === 3452 ? 1010 : item);
확실히, 질문은 몇 년 전부터입니다만, 현시점에서는 불변의 솔루션을 사용하는 것을 선호하고 있습니다.확실히 이 솔루션은ReactJS
.
자주 사용하는 경우 아래 기능을 제공합니다.
const itemReplacer = (array, oldItem, newItem) =>
array.map(item => item === oldItem ? newItem : item);
javascript에서 배열 요소를 교체하는 기능적 접근법:
const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];
및 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']
교환은 한 줄로 할 수 있습니다.
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);
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에 대한 자세한 내용은 를 참조하십시오.
가장 쉬운 방법은 언더스코어 및 맵 메서드와 같은 라이브러리를 사용하는 것입니다.
var items = Array(523,3452,334,31,...5346);
_.map(items, function(num) {
return (num == 3452) ? 1010 : num;
});
=> [523, 1010, 334, 31, ...5346]
var index = Array.indexOf(Array value);
if (index > -1) {
Array.splice(index, 1);
}
여기서 어레이에서 특정 값을 삭제할 수 있으며 동일한 인덱스에 따라 어레이에 값을 삽입할 수 있습니다.
Array.splice(index, 0, Array value);
어레이의 인덱스에서 개체를 교체하는 방법에 대해 고민하는 사람이 있다면 다음과 같은 해결책이 있습니다.
ID로 오브젝트의 인덱스를 찾습니다.
const index = items.map(item => item.id).indexOf(objectId)
Object.assign() 메서드를 사용하여 개체를 바꿉니다.
Object.assign(items[index], newValue)
간단한 설탕 신탁스 오넬리너를 원하는 경우 다음과 같이 할 수 있습니다.
(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);
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 arrayFindReplace(array, findValue, replaceValue){
while(array.indexOf(findValue) !== -1){
let index = array.indexOf(findValue);
array[index] = replaceValue;
}
}
여기 라이너가 하나 있어요.항목이 어레이에 포함되는 것을 전제로 합니다.
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;
이 문제는 루프를 사용하여 원래 어레이를 반복하고 일치하는 아레일의 위치를 다른 어레이에 추가한 후 해당 어레이를 루프하여 원래 어레이로 변경한 후 반환하고 화살표 함수를 사용했지만 일반 기능도 작동합니다.
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]
어레이에 새 항목을 대체할 오래된 항목이 많이 있는 경우 다음과 같이 사용할 수 있습니다.
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)
이것으로 충분하다
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'))
출력:
['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']
좋은 점은, 모든 어레이가.replace()
소유물.
언급URL : https://stackoverflow.com/questions/5915789/how-to-replace-item-in-array
'programing' 카테고리의 다른 글
PHP에서 "Unable to allocate memory for pool"이 발생하는 원인은 무엇입니까? (0) | 2022.11.22 |
---|---|
PHP의 숫자와 같은 문자를 증가시키는 방법은 무엇입니까? (0) | 2022.11.22 |
커스텀 커넥터를 사용하여 Django에서 MySQL/MariaDB 연결을 적절하게 끊는 방법 (0) | 2022.11.22 |
String Utils 입니다.EMPTY를 권장합니다. (0) | 2022.11.22 |
웹 서비스 URL 끝점을 변경하는 방법 (0) | 2022.11.21 |