gpt4 book ai didi

javascript - 在 JavaScript 中测试/检查字符串的最佳实践

转载 作者:行者123 更新时间:2023-12-04 07:21:07 24 4
gpt4 key购买 nike

我最近遇到了这个(无可否认的)教科书 JavaScript 练习,我在概念上遇到了问题,我被告知是“最佳实践”的两个解决方案。我意识到这是非常基本的东西;我只是想尽可能扎实地掌握这里的基本原理。
练习本身非常简单:编写一个函数来检查字符串是否包含相同数量的两个唯一字符(在本例中为 'x's 和 'o's)。该函数必须返回一个 bool 值并且不区分大小写。
我部分理解的第一个“最佳实践”解决方案是:

function XO(string) {
let x = str.match(/x/gi);
let o = str.match(/o/gi);
return (x && x.length) === (o && o.length);
}
我了解在函数的前两行中完成的基本正则表达式工作,但 && 逻辑运算符在函数的第三行和最后一行中的确切作用让我感到困惑。我遇到了麻烦,用简单的英语向自己解释 (a) 它的作用和 (b) 为什么像 return x === y 这样的东西在这种情况下,单独不是一个足够强大的解决方案。
我遇到的第二个“最佳实践”解决方案是:
const XO = str => {
str = str.toLowerCase().split('');
return str.filter(x => x === 'x').length === str.filter(x => x === 'o').length;
}

恐怕我不得不承认这个解决方案的大部分逻辑都让我无法理解,尽管我确实明白 .split('')正在运行以生成可以通过 .filter 运行的单个字符数组。 .

最佳答案

首先,match返回 null如果根本没有匹配项。如果你尝试取null的长度,会抛出错误。x && x.length有效,因为 a) 运算符短路:如果前者是“假的”,后者不会被执行(它不会改变结果)并返回最后一个真值,b)任何值都被强制为 bool 值 bool 上下文(例如作为 && 的操作数)

function XO(string) {
let x = str.match(/x/gi);
// x contains an array that has every match if any
// e.g. ["x", "x", "x"] or null

let o = str.match(/o/gi);
// same for "o"

return (x && x.length) === (o && o.length);
//
// Given x === null, y === null :
// (null && null.length) === (null && null.length)
// (false && null.length) === (false && null.length) <- boolean coercion
// false === false
// true
//
// Given x === ["x", "x"], y === ["y", "y"] :
// (["x", "x"] && ["x", "x"].length) === (["y", "y"] && ["y", "y"].length)
// (true && ["x", "x"].length) === (true && ["y", "y"].length)
// (true && 2) === (true && 2)
// 2 === 2
// true
}
第二个有其他技巧。它使用输入参数作为变量(这不太常见,但有效)。此外,它使用“箭头函数”而不是常规函数。它们有一些差异,但大多数情况下您可以认为 function a(x) { return 2*x; }作品为 const a = (x) => 2*x;
const XO = str => {
str = str.toLowerCase().split('');
// replace the argument string with an array of characters
// str = "xXyY".toLowerCase().split('')
// str = "xxyy".split("")
// str = ["x", "x", "y", "y"]

return str.filter(x => x === 'x').length === str.filter(x => x === 'o').length;
// ["x", "x", "y", "y"].filter(x => x === 'x').length === ["x", "x", "y", "y"].filter(x => x === 'y').length;
// ["x", "x"].length === ["y", "y"].length
// 2 === 2
// true
}

关于javascript - 在 JavaScript 中测试/检查字符串的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68493323/

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