Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rails有一个;试一试;方法用于所有对象。有没有一种方法可以在Javascript中执行类似的操作?_Javascript - Fatal编程技术网

Rails有一个;试一试;方法用于所有对象。有没有一种方法可以在Javascript中执行类似的操作?

Rails有一个;试一试;方法用于所有对象。有没有一种方法可以在Javascript中执行类似的操作?,javascript,Javascript,因为null和undefined不是JavaScript中的对象,我猜它可能是一个全局帮助函数 示例用法可能类似于: var a = { b: { c: { d: 'hello world!' } } }; tryPath(a, 'b', 'c', 'd'); // returns 'hello world!' tryPath(a, 'x', 'c', 'd'); // returns undefined var tryPath=函数tryPath(){ if(arguments.length

因为
null
undefined
不是JavaScript中的对象,我猜它可能是一个全局帮助函数

示例用法可能类似于:

var a = { b: { c: { d: 'hello world!' } } };
tryPath(a, 'b', 'c', 'd'); // returns 'hello world!'
tryPath(a, 'x', 'c', 'd'); // returns undefined
var tryPath=函数tryPath(){
if(arguments.length<2){
返回未定义;//无效
}否则{
变量对象=参数[0];
for(var i=1;i
您甚至可以用以下方法缩短它

function tryPath(object) {
    var path = Array.prototype.slice.call(arguments, 1);
    if (!path.length) return undefined;
    return path.reduce(function(result, current) {
        return result === undefined ? result : result[current];
    }, object);
}

var a = { b: { c: { d: 'hello world!' } } };
console.assert(tryPath(a, 'b', 'c', 'd') === 'hello world!');
console.assert(tryPath(a, 'x', 'c', 'd') === undefined);
console.assert(tryPath(a) === undefined);

您可以在不使用辅助函数的情况下完成相当简单的操作:

var a = { b: { c: { d: 'hello world!' } } };
a && a.b && a.b.c && a.b.c.d; // returns 'hello world!'
a && a.x && a.x.c && a.x.c.d; // returns undefined

Great的可能重复,只是它使用嵌套函数,因此速度可能较慢?
var a = { b: { c: { d: 'hello world!' } } };
a && a.b && a.b.c && a.b.c.d; // returns 'hello world!'
a && a.x && a.x.c && a.x.c.d; // returns undefined