2017-03-23 6 views

答えて

6

最初の要素がないコピーにはArray#sliceを使用できます。 forEach

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

 
arr.slice(1).forEach(function(value) { 
 
    console.log(value); 
 
});

+0

これはまさに私が探していたものです。 –

3

使用index

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

 
arr.forEach(function(value, index) { 
 
    if (index != 0) {console.log(value) } 
 
});

1

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

 
arr.forEach(function(value, index) { 
 
    return index == 0 ? true : console.log(value), true; 
 
});

+1

['Array#forEach'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)は戻り値を気にしません。 –

0
arr.forEach(function(value, index) { 
    if(index !== 0) { 
     console.log(value); 
    } 
}); 

この少し値がarray.slice(1).forEach(...)がエレガントですが、それは新しい配列を作成し最初の配列項目

+1

この配列 '[99,1,2,3,99,5,6]'はどうですか? – georg

+0

@georg、良い点私は編集を行います。ありがとう – goosmaster

0

に等しくない場合ステートメントはちょうど発射した場合。 forEach(配列インデックス)に渡された2番目のプロパティが0か、 "falsy"かどうかをチェックすることで、これを回避できます。

if (i) expression()

i && expression()へ...この方法は驚くほど簡潔になり:あなたの渡された関数は、単一の式を実行するために発生した場合、次の文を短くすることができます。

let array = [1, 2, 3, 4, 5] 
 

 
array.forEach(function (value, i) { 
 
    if (i) console.log(value) 
 
}) 
 

 
array.forEach(function (value, i) { 
 
    i && console.log(value) 
 
})

関連する問題