问题(来自Eloquent Javascript第2版,第4章,练习4):
编写一个函数deepEqual,它接受两个值,只有当它们是相同的值时返回true,或者是与对deepEqual的递归调用相比,其值也相等的对象.
测试用例:
var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// ? true
console.log(deepEqual(obj, {here: 1, object: 2}));
// ? false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// ? true
Run Code Online (Sandbox Code Playgroud)
我的代码:
var deepEqual = function (x, y) {
if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop))
return deepEqual(x[prop], y[prop]);
/*This is …Run Code Online (Sandbox Code Playgroud) 我最近开始学习JavaScript,并且在变量命名方面遇到了一些问题.例如,这是我通常在Ruby中所做的事情:
no_spaces = 'the gray fox'.gsub(/\s/, '')
=> "thegrayfox"
reversed = no_spaces.reverse()
=> "xofyargeht"
no_spaces
=> "thegrayfox"
reversed
=> "xofyargeht"
Run Code Online (Sandbox Code Playgroud)
但是,同样的事情在JavaScript中不起作用.这是发生的事情:
var noSpaces = 'the gray fox'.replace(/\s/g, '').split('')
noSpaces
=> [ 't', 'h', 'e', 'g', 'r', 'a', 'y', 'f', 'o', 'x' ]
var reversed = noSpaces.reverse().join('')
noSpaces
=> [ 'x', 'o', 'f', 'y', 'a', 'r', 'g', 'e', 'h', 't' ]
reversed
=> 'xofyargeht'
Run Code Online (Sandbox Code Playgroud)
在这里,它似乎reverse()是罪魁祸首,但它很可能与其他功能发生.我的代码中是否存在一个我没有意识到的问题,或者这只是关于JS的一个奇怪的问题?