Что не так с массивом javascript?
Получаю данные с стороннего API в виде строки ( по websocket):
```ws.onmessage = function (evt) {
let messageGateObj = JSON.parse(evt.data);
console.log('Array.isArray(messageGateObj.params) ', Array.isArray(messageGateObj.params));
let toString = {}.toString;
console.log('toString.call(messageGateObj.params)=', toString.call(messageGateObj.params)); //
[object Array]
}```
Меня интересует messageGateObj.params его структура при выводе:
[false,
{ asks: [ [Array], [Array] ], bids: [ [Array], [Array], [Array] ] },
'XRP_USDT'
]```
двумя способами проверил, что это является массив. Но методы массивов не работают на нем: length,splice
1) messageGateObj.params.length
2) messageGateObj.params.splice
3) messageGateObj.params[0]
Выдает "Cannot read property 'length' of undefined".
Наверное я что-то не замечаю. Что не так подскажите.
Вот полный код в нем ошибки:
```ws.onmessage = function (evt) {
console.log('typeof evt.data:', typeof evt.data);
let messageGateObj = JSON.parse(evt.data);
console.log('Array.isArray(messageGateObj.params) ', Array.isArray(messageGateObj.params));
console.log('messageGateObj.params', messageGateObj.params);
console.log('messageGateObj:', messageGateObj);
// console.log('messageGateObj.params.length', messageGateObj.params.length); // ошибка Cannot read property 'length' of undefined
console.log('messageGateObj.params.constructor.name === Array', messageGateObj.params.constructor.name === 'Array'); // ошибка Cannot read property 'constructor' of undefined
let toString = {}.toString;
console.log('toString.call(messageGateObj.params)=', toString.call(messageGateObj.params)); // [object Array]
};```
В консоли выводится:
`typeof evt.data: string
Array.isArray(messageGateObj.params) false
messageGateObj.params undefined
messageGateObj: { error: null, result: { status: 'success' }, id: 974
}
C:\nodejs\server\Current\gate\gatecurent\nodejs\lib\gate.js:130
console.log('messageGateObj.params.constructor.name === Array',
messageGateObj.params.constructor.name === 'Array'); // ошибка
Cannot read property 'constructor' of undefined`
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
Вы не замечаете, что у объекта messageGateObj нет свойства params.
Непосредственно перед обращением к messageGateObj.params.length выведите
console.log(messageGateObj);
Ваш let messageGateObj внутри анонимной функции function (evt) { ... } - локальная переменная. Снаружи этой функции Вы обращаетесь к какому-то другому объекту.
let messageGateObj = {
method: 'depth.update',
params: [ false, { asks: [Array], bids: [Array] }, 'XRP_USDT' ],
id: null
};
console.log(messageGateObj.params.length);