jQuery.map()


jQuery.map( array, callback )Возвращает: Array

Описание: Выполняет заданную функцию для каждого элемента массива (если задан массив) или каждого поля объекта (если задан объект) в отдельности. Значения, полученные в результате выполнения этой функции помещаются в новый массив и возвращаются как результат работы функции.

  • Добавлен в версии: 1.0jQuery.map( array, callback )

    • array
      Тип: Array
      The Array to translate.
    • callback
      Тип: Function( Object elementOfArray, Integer indexInArray ) => Object
      The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.
  • Добавлен в версии: 1.6jQuery.map( object, callback )

    • object
      Тип: Object
      The Object to translate.
    • callback
      Тип: Function( Object propertyOfObject, String key ) => Object
      The function to process each item against. The first argument to the function is the value; the second argument is the key of the object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.

If you wish to process a jQuery object — for example, $('div').map( callback ); — use .map() instead.

The $.map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $.map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.

Array-like objects — those with a .length property and a value on the .length - 1 index — must be converted to actual arrays before being passed to $.map(). The jQuery library provides $.makeArray() for such conversions.

1
2
3
4
5
6
7
8
9
10
// The following object masquerades as an array.
var fakeArray = { "length": 2, 0: "Addy", 1: "Subtracty" };
// Therefore, convert it to a real array
var realArray = $.makeArray( fakeArray )
// Now it can be used reliably with $.map()
$.map( realArray, function( val, i ) {
// Do something
});

The translation function that is provided to this method is called for each top-level element in the array or object and is passed two arguments: The element's value and its index or key within the array or object.

The function can return:

  • the translated value, which will be mapped to the resulting array
  • null or undefined, to remove the item
  • an array of values, which will be flattened into the full array

Примеры использования