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] +')'
JavaScript: Свойство length
Если элементы добавлялись в массив без пропусков, в порядке возрастания индекса (когда каждый элемент массива имеет индекс на единицу больше предыдущего), то с помощью свойства length можно узнать количество элементов в массиве. При добавлении новых элементов в массив, свойство length автоматически обновляется:
var arr = []; alert(arr.length); // 0 arr[0] = 23; alert(arr.length); // 1 arr[1] = 13; alert(arr.length); // 2
Свойство length в качестве значения содержит число, равное последнему (самому большому) используемому индексу + 1. Поэтому, если индексы элементам массива присваивать в произвольном порядке, свойство length не имеет смысла использовать для определения количества элементов:
var arr = []; arr[99] = "строка"; // Добавляем один элемент под индексом 99 alert(arr.length); // 100
Наиболее часто свойство length используется для перебора элементов массива в циклах:
var fruits = ["яблоко", "банан", "клубника", "персик"]; for(let i = 0; i < fruits.length; i++) alert(fruits[i]);
С помощью свойства length можно укорачивать массив с конца, для этого свойству присваивается значение, меньшее чем длина массива:
var arr = [1,2,3]; arr.length = 1; alert(arr[1]); // undefined. Остался только элемент под индексом 0
Если конструктору Array в качестве аргумента передать только один числовой аргумент, то будет создан пустой массив, у которого значение свойства length равно переданному в конструктор числу:
var arr = new Array(15); alert(arr.length); // 15
Тоже самое можно сделать, создав массив с помощью литерала и явно присвоив свойству length значение:
var arr = []; arr.length = 15; alert(arr.length); // 15
Примечание: присваивание свойству length произвольного значения, не добавляет в массив новых элементов, а просто изменяет значение свойства. В этом можно убедиться на простом примере:
var arr = []; arr.length = 15; alert("0" in arr); // false arr[0] = undefined; alert("0" in arr); // true
Так как свойство length в качестве значения содержит число, равное последнему (самому большому) используемому индексу + 1, его можно использовать в качестве индекса при добавлении новых элементов, вместо явного указания индекса:
arr = []; arr[arr.length] = 2; arr[arr.length] = 34;
Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru
JavaScript Array Length Property
The JavaScript array's length property measures the number of currently available "spots" in the array, whether these spots have been initialized with a value or not. Array length is also a "read/write" property, which means that your scripts can not only retrieve it, but also modify it.
An array's length property returns an integer greater or equal to zero (
This tutorial covers the Array length property. Are you looking for the String length property?
Getting an Array's Length in JavaScript
The length property is dynamic, and is automatically updated by the JavaScript interpreter (built into your web browser) as the length changes.
// Array constructor without arguments (length=0)
var arlene = new Array();
Array length is always one more than the highest array index number, because the first element of a JavaScript array is zero. (See Referencing array elements.)
The last element of an array of length 6 is " array[5] "
It is also possible to preset the array size (length) when declaring the array, by passing an integer to the new Array() constructor:
var arlene = new Array(7);
// We just declared an array of size 7 (length = 7)
alert( arlene.length.toString() );
Unsurprisingly, we get the following result:
Setting an Array's Length in JavaScript
In many other programming languages, setting the array size upon declaration is mandated. It is not the case with JavaScript, however, and it will increase your array size "on demand", as required by your scripts.
var arlene = new Array(7); // length = 7 (elements 0 through 6)
arlene[7] = "test 1";
arlene[8] = "test 2";
alert( arlene.length.toString() );
The script above demonstrates how the JavaScript interpreter will allocate more memory to your objects, if requested by your scripts.
Array Length is a Read/Write Property
Array length is a "read / write" property — your scripts can both retrieve it and set it. We saw above how to indirectly change an array length; our script will now explicitly assign a new length to an array.
// Declare an array of length 7
var arlene = new Array(7);
// Set its length to 9
arlene.length = 9;
// Get the current array size:
alert( arlene.length.toString() );
After declaring a size-7 array, our script sets the array length to 9. As expected, the alert returns an updated length:
Since the JavaScript interpreter takes care of expanding your array size as needed at runtime (during script execution), you will probably find yourself more often retrieving an array length than setting it.
The fact that JavaScript arrays use a zero-based index for their elements implies: (1) that the first element is Array[0] , and (2) that Array[Array.length-1] is the last array element (the index of the last element is one less than the number of elements).
Practically: the last element of an array of length 7 is Array[6] , since the element count starts at zero…
Test the Array Length Property
Interactively test the array length property by editing the JavaScript code below and clicking the Test Array Length Property button.
Test Array Length Property
Browser support for JavaScript array length property |
---|