gpt4 book ai didi

JavaScript 值在变量中未正确评估,但作为字符串正常工作

转载 作者:行者123 更新时间:2023-12-03 10:00:47 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why does a RegExp with global flag give wrong results?

(7 个回答)


2年前关闭。




我不确定为什么这个评估只在一个变量中而不是在一个字符串中时会有所不同。我看不出任何逻辑。

const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)


var word = 'hundred';
console.log('isNum with string:', isNum('hundred')); // true
console.log('isNum with variable:', isNum(word)); // false
console.log('words are equal:', word === 'hundred'); // true

最佳答案

isNum正在返回 false当它在同一字符串上被第二次调用时。改变顺序,看到同样的东西:

const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)


var word = 'hundred';
console.log('isNum with variable:', isNum(word)); // true
console.log('isNum with string:', isNum('hundred')); // false
console.log('words are equal:', word === 'hundred'); // true
g flag 记住最后一场比赛的位置。删除它以解决问题:
const numRegex = /hundred|thousand|million|billion|trillion/i;

Mozilla talks more about this :

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

关于JavaScript 值在变量中未正确评估,但作为字符串正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com