programing

jQuery에서 어레이를 루프하는 방법

bestcode 2022. 9. 26. 23:05
반응형

jQuery에서 어레이를 루프하는 방법

어레이를 루프하려고 합니다.다음 코드가 있습니다.

 var currnt_image_list= '21,32,234,223';
 var substr = currnt_image_list.split(','); // array here

어레이에서 모든 데이터를 꺼내려고 합니다.누군가 나를 올바른 길로 인도해 줄 수 있나요?


(갱신:여기서의 또 다른 답변은 jQuery 이외의 옵션을 훨씬 더 상세하게 설명하고 있습니다.세 번째 옵션은jQuery.each을 이용하다


4가지 옵션:

범용 루프:

var i;
for (i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

또는 ES2015+의 경우:

for (let i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

장점:알기 쉽고 jQuery에 의존하지 않으며 이해하기 쉽고 의미 유지에 문제가 없습니다.this루프 본체 내에서는 불필요한 함수 호출 오버헤드가 발생하지 않습니다(예를 들어 이론상으로는 더 빠른 속도입니다만, 실제로는 다른 문제가 발생할 가능성이 매우 높거나 상세합니다).

의 ES5forEach:

에는 ECMAScript5가 .forEach어레이를 쉽게 루프할 수 있도록 기능합니다.

substr.forEach(function(item) {
    // do something with `item`
});

문서에 대한 링크

이 외에도 기능이 .forEach;자세한 것에 대하여는, 상기의 회답을 참조해 주세요).

장점:선언형, 사용자가 리터레이터를 사용할 수 있는 경우 사전 빌드된 함수를 사용할 수 있습니다.루프 본체가 복잡한 경우 함수 호출의 범위를 지정하는 것이 편리할 수 있습니다.이러한 함수는 필요 없습니다.iyour scope.변수.

단점:사용하시는 경우this를 사용하고 , 라고 하는 .this의 범위 내에서forEach 내에서 수 해야 ) 두.forEachforEach라고 this콜백 중 또는 C) ES2015+ 화살표 기능을 사용하여 종료합니다.this 중 콜백에 this 되다undefined) 글로벌오브젝트 「 「」)의 경우).window 모드로 를 루즈 모드로 합니다.에는 두 .forEachFONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE:/FONT CHANGE가 탑재되어 있지 않습니다forEachIE8입니다(거기에서도 적절히 폴리필링할 수 없습니다).

의 ES2015+★for-of:

for (const s of substr) { // Or `let` if you want to modify it in the loop body
    // do something with `s`
}

동작의 상세한 것에 대하여는, 이 회답의 상단의 링크를 참조해 주세요.

장점:심플하고 알기 쉬운 어레이로부터의 엔트리에 포함되는 범위 변수(상기에서는 상수)를 제공합니다.

단점:IE 버전에서는 지원되지 않습니다.

jQuery.각각:

jQuery.each(substr, function(index, item) {
    // do something with `item` (or `this` is also `item` if you like)
});

(문서 링크)

장점:이 모든 이점은forEach게다가 jQuery를 사용하고 있기 때문에, 거기에 있는 것을 알 수 있습니다.

단점:사용하시는 경우this.this함수에 있는 다른 무언가를 의미합니다.

수 있어요.this다만, 다음의 어느쪽인가를 사용해 주세요.

jQuery.each(substr, $.proxy(function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}, this));

...또는Function#bind:

jQuery.each(substr, function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}.bind(this));

...또는 ES2015("ES6")에서 화살표 기능은 다음과 같습니다.

jQuery.each(substr, (index, item) => {
    // do something with `item` (`this` is the same as it was outside)
});

하지 말아야 할 일:

사용하지 않다for..in(혹은 만약 그렇다면 적절한 안전장치를 사용하여 실행한다.한 적이 ) 라고예요.for..in그것은 많은 사람들이 생각하는 것을 하지 않는다(그것은 훨씬 더 유용한 것을 한다. 「」입니다.for..in(배열의 인덱스가 아닌) 개체의 열거 가능한 속성 이름을 루프합니다.배열은 객체이며 기본적으로 열거 가능한 속성은 인덱스뿐이므로 대부분의 경우 무난한 배포에서 작동합니다.하지만 그걸 그냥 사용할 수 있다는 건 안전하지 않아요.다음은 http://jsbin.com/exohi/3에 대한 설명입니다.

위의 "하지 마세요"를 누그러뜨려야 합니다.어레이를하고 있는 총는 어떤 ~ 되어 있기 에 15 ~150,000의 범위 내에 ).length150,001)과 같은 적절한 세이프가드를 사용하는 경우hasOwnProperty하는 것은 ).for..in입력된 인덱스만 열거되기 때문에 불필요한 루프가 많이 발생하지 않도록 하는 매우 합리적인 방법이 될 수 있습니다.

jQuery.each()

jQuery.each()

jQuery.each(array, callback)

배열 반복

jQuery.each(array, function(Integer index, Object value){});

오브젝트 반복

jQuery.each(object, function(string propertyName, object propertyValue){});

:

var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) { 
  console.log(index, val)
});

var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
  console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

배열의 javascript 루프

포루프

for (initialExpression; condition; incrementExpression)
  statement

var substr = [1, 2, 3, 4];

//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
  console.log("loop", substr[i])
}

//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
  console.log("reverse", substr[i])
}

//step loop
for(var i = 0; i < substr.length; i+=2) {
  console.log("step", substr[i])
}

을 위해

//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
    console.log(substr[i]) //note i returns index
}

을 위해

for(var i of subs) {
    //can use break;
    console.log(i); //note i returns value
}

각각

substr.forEach(function(v, i, a){
    //cannot use break;
    console.log(v, i, a);
})

자원.

MDN 루프 및 반복기

...for프프: :

var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
  alert(substr[i]);
}

옵션 1 : 기존 루프

기본

의 통인 afor-loop 3가지 요소-루프에는 다음 3가지컴포넌트가 있습니닸다.

  1. 초기화 : 룩블록이 처음 실행되기 전에 실행됩니다.
  2. condition : 루프 블록이 실행되기 전에 매번 상태를 체크하고 false일 경우 루프를 종료합니다.
  3. after think : 루프 블록 실행 후 매번 실행됨

이 세가지 부분들은 각각 다른 측면으로부터이들 3개의 컴포넌트는 서로 다른컴포넌트에 의해에 의해 분리되다.;기호.이 세가지 구성 요소의 기호. 콘텐츠, 이는 가장 최소한의 이들 3개의 컴포넌트각각에대한 콘텐츠는 옵션입니다.즉,적은 콘텐츠입니다 가장 다음 중 의미한다 선택 사항입니다.for가능한:-loop-루프 가능:

for (;;) {
    // Do stuff
}

물론, 너필요가 있습니다 포함할 물론, 다음 명령어를을 포함해야 할 것이다.if(condition === true) { break; }또는또는if(condition === true) { return; }안쪽 어디에선가 그 그 안 어딘가에for-loop 달리는 중단시키기 위해.-루프를눌러 실행을 중지합니다.

단, 일반적으로 초기화는 인덱스를 선언하기 위해 사용되며 조건은 인덱스를 최소값 또는 최대값과 비교하기 위해 사용되며 이후 고려사항은 인덱스를 증가시키기 위해 사용됩니다.

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

기존 -루프를 사용하여 어레이를 루프합니다.

어레이를 루프하는 기존의 방법은 다음과 같습니다.

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

반대로 루프하는 경우는, 다음과 같이 실시합니다.

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

단, 다음과 같은 다양한 종류가 있습니다.

for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

...아니면 이건...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... 또는 이것:

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}

어떤 것이 가장 적합한지는 대부분 개인의 취향과 구현하려는 특정 사용 사례에 달려 있습니다.

주의:

이러한 변형은 모두 Very Old 브라우저를 포함한 모든 브라우저에서 지원됩니다.


옵션 2 : -루프

한 대신할 수에 한가지 대안 있는 것은for-loop-루프는은while-loop. 배열을 통해 재생하려면 이:-루프 할 수 있었다.같이 하십시오 다음과어레이를 루프하려면.

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
주의:

전통적인 종래와 같은처럼for-loops, -오브젝트,while가장 오래된 브라우저에서도 지원되고 있습니다.

은, 1, 개, 개, 개, 개, 개 으로 고쳐 쓸 수.for를 들어 . ★★★★★★★★★★★★★★★★★,while 동작합니다.- 「 loop 」 、 「 loop 」 、 「 loop 」 。for- - : : :

for(var key = 0;value = myArray[key++];){
    console.log(value);
}

옵션 3 :및

JavaScript 에서는, 다음의 조작도 가능합니다.

for (i in myArray) {
    console.log(myArray[i]);
}

이것은 인 것과 행동을 에 주의해서 사용해야 합니다.for모든 경우 루프이며 고려해야 할 잠재적 부작용이 있습니다.자세한 내용은 어레이 반복에서 "for...in"을 사용하는 것이 좋지 않은 이유를 참조하십시오.자세한 것은, 을 참조해 주세요.

의 대체 수단으로서 「」도 있습니다.다음 예시는 의 차이를 나타내고 있습니다.for...of와 '루프'의for...in :디세이블화:

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}
주의:

의 어떤 버전도 Internet 를 고려해야 .for...of(Edge 12+는 가능) 및 그 자체for...inIE10 ie ie ie ie ie ie ie ie ie ie.


옵션 4:

「 」의 For는 -syslog입니다.Array.prototype.forEach()는 다음과 구문을

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
주의:

Array.prototype.forEach()IE9+로 하다


옵션 5:

앞서 인 4가지 도 가지고 있었습니다.foreach★★★★★★ 。

다음 구문을 사용합니다.

$.each(myArray, function(key, value) {
    console.log(value);
});

jQuery 함수를 사용합니다.

다음은 예를 제시하겠습니다.

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 
});

jQuery each()다른 방법도 있지만, 각각은 이 목적을 위해 설계되어 있습니다.

$.each(substr, function(index, value) { 
  alert(value); 
});

그리고 마지막 숫자 뒤에 쉼표를 넣지 마세요.

화살표 기능 및 보간 기능이 있는 ES6 구문:

var data=["a","b","c"];
$(data).each((index, element) => {
        console.log(`current index : ${index} element : ${element}`)
    });

'어울리다'를 사용할 수 요.for() 디세이블로그:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

이것을 시험해 보세요.

$.grep(array, function(element) {

})

$.map(데이터, 함수(elem) {...})

$.map(data,function(elem){
   console.log(elem);
})
            
   

다른 방법으로 어레이/문자열을 반복하고 부작용 발생

var str = '21,32,234,223';
var substr = str.split(',');

substr.reduce((a,x)=> console.log('reduce',x), 0)        // return undefined

substr.every(x=> { console.log('every',x); return true}) // return true

substr.some(x=> { console.log('some',x); return false})  // return false

substr.map(x=> console.log('map',x));                    // return array
 
str.replace(/(\d+)/g, x=> console.log('replace',x))      // return string

  for(var key in substr)
{
     // do something with substr[key];

} 

언급URL : https://stackoverflow.com/questions/3943494/how-to-loop-through-array-in-jquery

반응형