Javascript length function example

What is Javascript Length?

In this article, we look at what the Javascript length function does, where it could be used, and its limitations.

Table of Contents

What is Javascript Length?

Before we take a look at the code and its uses let’s first understand what the Length function in javascript does.

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings. I’ve explained each case in detail below.

Syntax of Javascript Length function

X.length //returns the length of X 

Here X can be either a string or an array.

Using Javascript Length on strings:

While using Javascript length on a string, the function returns the number of characters present in the string. And in case the string is empty it returns 0.

const xyz = "Hello World!"; console.log(xyz.length); // Output: 12 

Using Javascript Length on Arrays:

While using Javascript length on an array, the function returns the number of elements in the array. And similarly it returns 0 in the array is empty.

const xyz = ['bat', 'ball', 'mat', 'pad']; console.log(xyz.length); // Output: 4 

Note: While dealing with the length function remember that the length of an object is always greater than the index of it’s last element.

Источник

String: length

The length data property of a String value contains the length of the string in UTF-16 code units.

Try it

Value

Property attributes of String: length
Writable no
Enumerable no
Configurable no

Description

This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it’s possible for the value returned by length to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.

Читайте также:  Mysqli fetch php примеры

The language specification requires strings to have a maximum length of 2 53 — 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device’s memory, so implementations tend to lower the threshold, which allows the string’s length to be conveniently stored in a 32-bit integer.

  • In V8 (used by Chrome and Node), the maximum length is 2 29 — 24 (~1GiB). On 32-bit systems, the maximum length is 2 28 — 16 (~512MiB).
  • In Firefox, the maximum length is 2 30 — 2 (~2GiB). Before Firefox 65, the maximum length was 2 28 — 1 (~512MiB).
  • In Safari, the maximum length is 2 31 — 1 (~4GiB).

For an empty string, length is 0.

The static property String.length is unrelated to the length of strings. It’s the arity of the String function (loosely, the number of formal parameters it has), which is 1.

Since length counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:

function getCharacterLength(str)  // The string iterator that is used here iterates over characters, // not mere code units return [. str].length; > console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 

Examples

Basic usage

const x = "Mozilla"; const empty = ""; console.log(`$x> is $x.length> code units long`); // Mozilla is 7 code units long console.log(`The empty string has a length of $empty.length>`); // The empty string has a length of 0 

Strings with length not equal to the number of characters

const emoji = "😄"; console.log(emoji.length); // 2 console.log([. emoji].length); // 1 const adlam = "𞤲𞥋𞤣𞤫"; console.log(adlam.length); // 8 console.log([. adlam].length); // 4 const formula = "∀𝑥∈ℝ,𝑥²≥0"; console.log(formula.length); // 11 console.log([. formula].length); // 9 

Assigning to length

Because string is a primitive, attempting to assign a value to a string’s length property has no observable effect, and will throw in strict mode.

const myString = "bluebells"; myString.length = 4; console.log(myString); // "bluebells" console.log(myString.length); // 9 

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 May 31, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

.length

Свойство, которое возвращает количество элементов в массиве.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Свойство length возвращает количество элементов в массиве. Если элементов нет, то свойство возвращает 0.

Пример

Скопировать ссылку «Пример» Скопировано

 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс']console.log(series.length)// 4 const empty = []console.log(empty.length)// 0 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс'] console.log(series.length) // 4 const empty = [] console.log(empty.length) // 0      

Как понять

Скопировать ссылку «Как понять» Скопировано

Свойство length хранит количество ячеек в массиве. Строго говоря, количество ячеек может быть больше, чем количество элементов в массиве, но на практике они почти всегда совпадают.

Значение свойства length — целое положительное число в диапазоне от 0 до 2 32 .

Запись в свойство length

Скопировать ссылку «Запись в свойство length» Скопировано

Свойство length перезаписываемое, вы можете записать в него любое число из диапазона возможных значений. Это изменит количество ячеек массива.

Если уменьшить значение свойства length , то из конца массива будут отброшены элементы, которые не входят в новый размер массива:

 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс']console.log(series.length)// 4 series.length = 2console.log(series)// ['Кремниевая долина', 'Игра престолов'] const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс'] console.log(series.length) // 4 series.length = 2 console.log(series) // ['Кремниевая долина', 'Игра престолов']      

Если увеличить значение свойства length , то в конец массива добавятся пустые ячейки. Значение в них не будет установлено и они будут игнорироваться при обходе:

 const todos = ['купить молока', 'почитать Доку']console.log(todos.length)// 2 todos.length = 4console.log(todos)// ['купить молока', 'почитать Доку', ] todos.forEach(function(todo, index)  console.log(`$. todo`)>)// 1. купить молока// 2. почитать Доку const todos = ['купить молока', 'почитать Доку'] console.log(todos.length) // 2 todos.length = 4 console.log(todos) // ['купить молока', 'почитать Доку', ] todos.forEach(function(todo, index)  console.log(`$index + 1>. todo`) >) // 1. купить молока // 2. почитать Доку      

Случаи, когда length не совпадает с количеством элементов в массиве

Скопировать ссылку «Случаи, когда length не совпадает с количеством элементов в массиве» Скопировано

Корректнее всего говорить, что свойство length хранит количество ячеек доступных для записи в массиве, а не количество элементов. Они почти всегда совпадают, но есть случаи, когда в массиве больше ячеек, чем значений. Разберём эти случаи.

1️⃣ При создании пустого массива с помощью конструктора new Array ( ) можно указать количество ячеек в массиве. Тогда количество ячеек и количество элементов не будут совпадать:

 const emptyArray = new Array(100)console.log(emptyArray.length)// 100 const emptyArray = new Array(100) console.log(emptyArray.length) // 100      

Такой проблемы не случится, если создавать массив с помощью литерала:

 const anotherEmptyArray = []console.log(anotherEmptyArray.length)// 0 const anotherEmptyArray = [] console.log(anotherEmptyArray.length) // 0      

2️⃣ При записи нового элемента в индекс далеко за пределами массива. В этом случае между последним элементом и новым появляется «дыра» из пустых ячеек:

 const priorities = ['спать', 'есть', 'пить']console.log(priorities.length)// 3 priorities[999] = 'работать'console.log(priorities.length)// 1000console.log(priorities)// ['спать', 'есть', 'пить', , 'работать'] const priorities = ['спать', 'есть', 'пить'] console.log(priorities.length) // 3 priorities[999] = 'работать' console.log(priorities.length) // 1000 console.log(priorities) // ['спать', 'есть', 'пить', , 'работать']      

3️⃣ При ручном увеличении значения свойства length :

 const todos = ['купить молока', 'почитать Доку']console.log(todos.length)// 2 todos.length = 4console.log(todos)// ['купить молока', 'почитать Доку', ] const todos = ['купить молока', 'почитать Доку'] console.log(todos.length) // 2 todos.length = 4 console.log(todos) // ['купить молока', 'почитать Доку', ]      

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Свойство length используется при обходе массивов с помощью классических циклов for или while . На практике такие циклы уже встречаются редко, но это идиоматический код, который нужно знать. Если применить length неправильно, то можно перебрать не все элементы или сделать бесконечный цикл.

Классический код, который напечатает все элементы массива:

 const movies = ['Good Will Hunting', 'Raining Man', 'Beautiful Mind']for (let i = 0; i < movies.length; i++)  console.log(movies[i])> const movies = ['Good Will Hunting', 'Raining Man', 'Beautiful Mind'] for (let i = 0; i  movies.length; i++)  console.log(movies[i]) >      

🛠 Чаще всего к свойству обращаются, когда хотят проверить, пустой массив или нет:

 const movies = [] if (movies.length === 0)  console.log('Вы посмотрели все фильмы!')> const movies = [] if (movies.length === 0)  console.log('Вы посмотрели все фильмы!') >      

🛠 Не записывайте вручную значения в length . Хотя это и возможно, на практике такой код плохо читается. Он может неприятно удивить других разработчиков из-за того, что изменяет размер массива. Об этом побочном эффекте знают не все.

Источник

Function: length

The length data property of a Function instance indicates the number of parameters expected by the function.

Try it

Value

Property attributes of Function: length
Writable no
Enumerable no
Configurable yes

Description

A Function object’s length property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function.

The Function constructor is itself a Function object. Its length data property has a value of 1 .

Due to historical reasons, Function.prototype is a callable itself. The length property of Function.prototype has a value of 0 .

Examples

Using function length

.log(Function.length); // 1 console.log((() => >).length); // 0 console.log(((a) => >).length); // 1 console.log(((a, b) => >).length); // 2 etc. console.log(((. args) => >).length); // 0, rest parameter is not counted console.log(((a, b = 1, c) => >).length); // 1, only parameters before the first one with // a default value are counted 

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 Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью