length
Может не в тему, хотя очень близко к ней. Возник вопрос, можно ли из времени вытащить вторую цифру без первой. Понимаю, вопрос может показать не понятным, потому привожу пример:
d=new Date()
h=d.getHours()
m=d.getMinutes()
s=d.getSeconds()
и я вывожу минуты:
document.write(m)
получаю, например:
45
как можно, если можно, вытащить 5?
Буду благодарен за отзывчивость
Берите остаток от деления на 10.
СпасибО! Все оказалось намного проще, чем я думал=)
такой вопрос:
прописываю:
x=document.getElementById(id_name)
document.write(x.length)
браузер выводит:
undefined
не могу понять в чем причина, подскажите пожалуйста
Кто Вам сказал, что метод getElementById возвращает массив?
.length работает и для строк (длина строки).
С другой стороны, getElementById возвращает объект, а не строку и не массив.
//Записываем значение:
tmad[‘sss’] = ‘e’;
tmad[‘ccc’] = 5;
// Выводим длину:
alert(tmad.length);
выводит нуль. Как вывести длину в этом случае?
PS. Сам понимаю что небылица какая-то.
попробуйте вместо sss и ссс использовать индексы и все получится. Ну или вместо Array: Object
Кстати Sobakin
getElementById() — возвращает действительно не массив.
но вот getElementById().innerHTML (кроссброузерно) возвращает массив
.innerHTML возвращает строку.
а строка это массив символов
В JavaScript — строка относится к неизменяемым значениям, она ведет себя как массив символов, но на самом деле таковым не является. Любая попытка изменить строку, просто-напросто возвращает новую строку. Массивы же, как раз относятся к изменяемым типам, так как по сути, массив — объект.
почему не срабатывает show()?)
запихните скрипт вывода из конца вашего кода, в функцию show.
1. нужно добавить отмену нативного действия ссылки с атрибутом href
Show
2. на странице два элемена с и функция изменяет первый (который спрятан вместе с родителем )
ниже рабочий код, от него и пляшите:
function show()Show
как сложить все цифры массива?
через length мы можем брать последнее значение как взять 1?
var arr = [1, 2, 3, 4, 5];
console.log(arr[0]); // 1
Не получается решить такой задачу, может кто знает как:
Есть массив, в котором значения это цифры от 0 до 9:
1) Посчитать сколько раз в массиве встречается каждая цифра.
2) Удвоить каждый четный элемент массива, и если после удвоения он окажется больше 9,
то вычесть из него 9. Далее посчитать сумму всех значений массива, и если сумма не кратна 10, то добавить к последнему элементу массива такое число, чтобы сумма элементов массива стала кратна 10.
Є масив mass, що складається з n рядків.
Довжину рядка я можу визначити mess[і].length. А як визначити кількість n рядків в куплеті??
var pageSettings = red: 200,
green: 200,
blue: 200,
background:['https://pictures.s3.yandex.net/background.jpg', 'https://pictures.s3.yandex.net/cover-color.jpg', 'https://pictures.s3.yandex.net/cover-grid.jpg', 'https://pictures.s3.yandex.net/cover-typo.jpg', 'https://pictures.s3.yandex.net/cover-wall.jpg'],
>
var bgColor = 'rgb(' + pageSettings.red +', ' + pageSettings.green +', ' + pageSettings.blue + ')';
document.body.style.backgroundColor = bgColor;
var header = document.getElementById('main-header');
console.log(header);
header.style.backgroundImage = 'url(https://pictures.s3.yandex.net/cover-grid.jpg)';
Установите для веб-страницы фон «шапки» header, выбрав последний элемент массива pageSettings.background вызовом свойства length
подскажите пожалуйста как это сделать?
var pageSettings = red : 200,
green : 200,
blue : 200,
background: ['https://pictures.s3.yandex.net/background.jpg' , 'https://pictures.s3.yandex.net/cover-color.jpg' , 'https://pictures.s3.yandex.net/cover-grid.jpg' , 'https://pictures.s3.yandex.net/cover-typo.jpg' , 'https://pictures.s3.yandex.net/cover-wall.jpg' ]
>;
var bgColor = 'rgb(' + pageSettings.red + ' , ' + pageSettings.green + ', ' + pageSettings.blue +')';
document.body.style.backgroundColor = bgColor;
var header = document.getElementById('main-header');
console.log(header);
header.style.backgroundImage = 'url(' + pageSettings.background[pageSettings.background.length - 1] +')'
Array: length
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Try it
Value
A nonnegative integer less than 2 32 .
Property attributes of Array: length | |
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
Description
The value of the length property is a nonnegative integer with a value less than 2 32 .
const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length
The array object observes the length property, and automatically syncs the length value with the array's content. This means:
- Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
- Setting any array index (a nonnegative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
- Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.
When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.
const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, ] arr.forEach((element) => console.log(element)); // 1 // 2
Examples
Iterating over an array
In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.
const numbers = [1, 2, 3, 4, 5]; const length = numbers.length; for (let i = 0; i length; i++) numbers[i] *= 2; > // numbers is now [2, 4, 6, 8, 10]
Shortening an array
The following example shortens the array numbers to a length of 3 if the current length is greater than 3.
const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) numbers.length = 3; > console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; the extra elements are deleted
Create empty array of fixed length
Setting length to a value greater than the current length creates a sparse array.
const numbers = []; numbers.length = 3; console.log(numbers); // [empty x 3]
Array with non-writable length
The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.
"use strict"; const numbers = [1, 2, 3, 4, 5]; Object.defineProperty(numbers, "length", writable: false >); numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]' numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.