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