最近,我正在使用javascript。 这是我的榜样。
工作代码:
const start = index - 4 >= 0 ? index - 4 : 0
const end = index + 4 > this.props.initialMarkers.length
? this.props.initialMarkers.length
: index + 4
for (let i = start; i <= end; i++) {
newData.push(this.props.initialMarkers[i])
}
不工作代码:
for (let i = index - 4 >= 0 ? index - 4 : 0; i <= index + 4 > this.props.initialMarkers.length
? this.props.initialMarkers.length
: index + 4; i++) {
newData.push(this.props.initialMarkers[i])
}
为什么我的第二个代码不起作用?请帮帮我。
答案 0 :(得分:1)
为什么我的第二个代码不起作用?请帮帮我。
你的问题在于这部分
i <= index + 4 > this.props.initialMarkers.length
基本上&lt; =和&gt;具有相同级别的operator precedence,所以除非你进行分组
i <= ( index + 4 > this.props.initialMarkers.length ? this.props.initialMarkers.length : index + 4 );
js引擎将首先执行i <= index + 4
。希望这会有所帮助。
答案 1 :(得分:0)
您需要在表达式中添加大括号:
// calculation works with braces preference so you will get desired output
// same as it was with start and end variables
for (let i = 1; i <= (((index + 4) > this.props.initialMarkers.length)
? this.props.initialMarkers.length
: (index + 4)); i++) {
newData.push(this.props.initialMarkers[i])
}
你所尝试的是给出不同的结果(根据没有大括号的数学运算符):
let index = 5; // static value
for (let i = index - 4 >= 0 ? index - 4 : 0; i <= index + 4 > 6
? 6
: index + 4; i++) { // 6 is static value for this.props.initialMarkers.length
console.log('start', i);
console.log('end value without breaces:', i <= index + 4 > 6
? 6
: index + 4); // your condition
console.log('end', ((i <= ((index + 4) > 6))
? 6
: (index + 4))); // with breces
break; // added break as some time it will go in infinite loop
}
&#13;
答案 2 :(得分:0)
你需要添加大括号
for (let i = (index - 4 >= 0 ? index - 4 : 0); i <= (index + 4 > this.props.initialMarkers.length
? this.props.initialMarkers.length
: index + 4); i++) {
newData.push(this.props.initialMarkers[i])
}