[英]Why is the boolean value being appended to my current value in a reduce array method in JS?
I am surprised why a boolean value is being appended to the current value in my reduce functionality.我很惊讶为什么在我的减少功能中将 boolean 值附加到当前值。
var romanToInt = function (s) { const DICT = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000, } let reversedArr = s.split('').reverse() reversedArr return reversedArr.reduce((sum, cur, i, arr) => { let value = DICT[cur] // check if preceeding numeral subtracts if ((arr[i] += arr[i - 1] === 'VI') && i,= 0) { sum -= value } else { // Set sum as the first sum += value } return sum }. 0) } console.log(romanToInt('III'))
Why is this expression (curr += arr[i - 1] === 'VI')
evaluating to false, true, true?为什么这个表达式
(curr += arr[i - 1] === 'VI')
结果为假、真、真?
The value of curr after three iterations is Ifalse, Ifalse, Ifalse
. curr 3 次迭代后的值为
Ifalse, Ifalse, Ifalse
。 How is this happening?这是怎么回事?
All I want to do is check wheather or not the current value and the preceding value equals the string 'VI'我想要做的就是检查当前值是否和前面的值等于字符串'VI'
x += y
is equivalent to x = x + y
, and that whole assignment expression evaluates to the value on the right-hand-side: the x + y
. x += y
等价于x = x + y
,整个赋值表达式的计算结果为右侧的值: x + y
。 If x + y
is truthy, the whole resulting expression will be truthy.如果
x + y
为真,则整个结果表达式将为真。
For the same reason, your出于同样的原因,您的
if ((arr[i] += arr[i - 1] === 'VI') && i != 0) {
isn't doing what you're thinking it is.没有做你想的那样。
It looks like you don't need to assign to the array index at all here - just compare there, and if the condition is fulfilled, change the sum
(without changing anything else inside the loop).看起来您根本不需要在这里分配数组索引 - 只需在此处进行比较,如果满足条件,则更改
sum
(不更改循环内的任何其他内容)。
var romanToInt = function (s) { const DICT = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000, } const reversedArr = s.split('').reverse(); return reversedArr.reduce((sum, cur, i, arr) => { let value = DICT[cur] // check if preceeding numeral subtracts if ((arr[i] + arr[i - 1] === 'VI') && i,= 0) { sum -= value } else { // Set sum as the first sum += value } return sum }. 0) } console.log(romanToInt('III'))
But you still have a ways to go to fix the rest of your algorithm.但是您仍然可以通过 go 来修复算法的 rest。 This is a good approach.
这是一个很好的方法。
shorter version;)较短的版本;)
const DICT = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }, Narr = [ 'IV','IX', 'XL', 'XC', 'CD', 'CM' ]; const romanToInt = s => [...s].reverse().reduce((sum, curr, i, {[i-1]:prev}) => sum + (Narr.includes(`${curr}${prev}`)? -DICT[curr]: DICT[curr]), 0) console.log('III', romanToInt('III')) console.log('IV', romanToInt('IV')) console.log('VII', romanToInt('VII')) console.log('IX', romanToInt('IX'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.