В соответствии с требованием кода в Leetcode ниже рабочий код.
var depthSum = function (nestedList, depth=1) {
var res = 0;
nestedList.forEach((val) => {
if (val.isInteger() === false) {
res += depthSum(val.getList(), depth + 1);
} else {
res += val.getInteger() * depth;
}
});
return res;
};
Вы не можете использовать Array.isArray()
, потому что все члены вернут false.а также вы не можете получить доступ к значениям или списку напрямую.Вам необходимо получить доступ через их API.Входные данные для функции - это не просто массив.См. Тип ввода и API-интерфейсы, представленные в спецификации, следующим образом:
* function NestedInteger() {
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* @return {boolean}
* this.isInteger = function() {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* @return {integer}
* this.getInteger = function() {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* @return {void}
* this.setInteger = function(value) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
* @return {void}
* this.add = function(elem) {
* ...
* };
*
* Return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer
* @return {NestedInteger[]}
* this.getList = function() {
* ...
* };
* };
*/
/**
* @param {NestedInteger[]} nestedList
* @return {number}
*/