假设我有一个像这样的数组
console.log(1,2);
console.log(2,3);
console.log(3,4);
;
如何获得这样的输出?
for (var i = 0; i < data.length; i++) {
/* Dont know what to do */
}
依此类推......截至目前这是我的代码
(selectedDestination.modeOfTransport || {}).value === 'Driving'
// or (to avoid prototype inheritance)
(selectedDestination.modeOfTransport || Object.create(null)).value === 'Driving'
答案 0 :(得分:2)
您可以使用reduce将最后一个元素作为新元素返回。
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
data.reduce((a, b) => (console.log(a, b), b));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:1)
您只需在循环中阵列结束前停止一步并打印当前值和下一个值
var data = [1,2,3,4,5,6,7,8,9,0]
for (var i = 0; i < data.length -1; i++) {
console.log(data[i], data[i+1]);
}
答案 2 :(得分:0)
for (var i = 0; i < data.length; i++) {
if (i+1 < data.length) {
console.log(data[i], data[i+1]);
} else {
console.log("finished")
}
或只是
for (var i = 0; i < data.length; i++) {
if (i+1 < data.length-1) {
console.log(data[i], data[i+1]);
}
您需要使用else阻止index out of bound exception