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



我最近遇到了这个(诚然(教科书式的JavaScript练习,我在概念上很难理解我被告知的两个解决方案是";最佳实践"我意识到这是非常基本的东西;我只是想尽可能扎实地掌握这里的基本原理。

练习本身很简单:编写一个函数,检查字符串是否包含相同数量的两个唯一字符(在本例中为'x'和'o'(。函数必须返回布尔值并且不区分大小写。

第一个";最佳实践";我部分理解的解决方案是:

function XO(string) {
let x = str.match(/x/gi);
let o = str.match(/o/gi);
return (x && x.length) === (o && o.length);
}

我理解函数前两行中所做的regex的基本工作,但&第三个&函数的最后一行让我感到困惑。我很难用通俗的英语向自己解释(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(运算符短路:如果前者是"1";falsy";,后者不执行(它不会改变结果(,并且返回最后一个truthy值,b(在布尔上下文中,任何值都被强制为布尔值(例如,作为&&的操作数(

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
}

最新更新