gpt4 book ai didi

javascript - 将元素插入数组,其中对象由用户指定

转载 作者:行者123 更新时间:2023-11-28 01:35:09 24 4
gpt4 key购买 nike

我正在尝试从 html 手动指定对象“data1.authNames”和“data2.authNames”并尝试将对象推送到其上。我得到“无法调用未定义的方法‘推送’”我哪里出错了?

HTML

<body ng-controller="MainCtrl">
<button ng-click="setAuthName('data1.authNames')">Button1</button>
<button ng-click="setAuthName('data2.authNames')">Button2</button>
</body>

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.data1 = $scope.data2 = {};
$scope.data1.authNames = [];
$scope.data2.authNames = [];

$scope.setAuthName = function(obj){
$scope.obj.push("Hello");
}

});

演示:http://plnkr.co/edit/xJ42UxQBVYYyFg8ljLDu?p=preview

最佳答案

这样做:

$scope.setAuthName = function(obj){
getProp($scope, obj).push("Hello");
};

function getProp(obj, prop){
var parts = prop.split('.');
var _ref = obj;
for(var i = 0; i < parts.length; i++){
var part = parts[i];
if(i === parts.length - 1)
return _ref[part];
else
_ref = _ref[part] || {};
}
}

编辑:您还有其他错误,请看一下:

app.controller('MainCtrl', function($scope) {
$scope.data1 = { authNames: [] };
$scope.data2 = { authNames: [] };

$scope.setAuthName = function(obj){
var o = getProp($scope, obj);
o.push("Hello");
console.log(o);
}

function getProp(obj, prop){
var parts = prop.split('.');
var _ref = obj;
for(var i = 0; i < parts.length; i++){
var part = parts[i];
if(i === parts.length - 1)
return _ref[part];
else
_ref = _ref[part] || {};
}
}
});

关于javascript - 将元素插入数组,其中对象由用户指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21620477/

24 4 0
文章推荐: html - 左侧菜单的问题
文章推荐: 两个 Date() 之间的 JavaScript 差异(以月为单位)
文章推荐: javascript - ESRI javascript API TOC 不适用于 TitledMapService
文章推荐: javascript - 检查外部 HTML 触发的事件