In this chapter, we will look at the built-in JavaScript array methods.
Object.keys(obj)
JavaScript has a built-in Object.keys (obj) method, which returns the keys of an object as an array. It is supported everywhere except IE <9:
6 |
var keys = Object.keys(user); |
8 |
alert(keys); // name, age |
In older browsers, the analog will be the cycle:
for ( var key in user) keys.push(key); |
Importance: 3
Go through the array nested loop.
For each element, we will look for whether this was already. If it was, ignore:
01 |
function unique(arr) { |
07 |
var str = arr[i]; // для каждого элемента |
08 |
for ( var j=0; j // ищем, был ли он уже? |
09 |
if (result[j] == str) continue nextInput; // если да, то следующий |
17 |
var strings = [ "кришна" , "кришна" , "харе" , "харе" , |
18 |
"харе" , "харе" , "кришна" , "кришна" , "8-()" ]; |
20 |
alert( unique(strings) ); // кришна, харе, 8-() |
Let's see how fast it will work.
Suppose there are 100
elements in an array. If they are all the same, then result
will consist of one element and the nested loop will be executed immediately. In this case, everything is fine.
And if all, or almost all the elements are different?
In this case, for each element you will need to bypass the entire current array of results, then add to this array.
-
- For the first element, this will cost
0
operations to access the result
elements (it is empty for now).
- For the second element, this will cost
1
operation to access the result
elements.
- For the third element, this will cost
2
operations to access the result
elements.
- ... For the nth element - it will cost
n-1
operations to access the result
elements.
Total 0 + 1 + 2 + ... + n-1 = (n-1)*n/2 = n 2 /2 - n/2
(as the sum of an arithmetic progression), that is, the number of operations grows approximately like a square from n
.
This is a very fast growth. For 100
elements - 4950
operations, for 1000
- 499500
(according to the formula above).
Therefore, this solution is suitable only for small arrays. Instead of the nested for
you can use arr.indexOf
, the situation will not change, since indexOf
also looking for a brute force.
The best technique for choosing unique lines is to use an auxiliary object. After all, the name of a property in an object is, on the one hand, a string, and on the other, it is always unique. Repeated writing to a property with the same name will overwrite it.
For example, if "харе"
got into the object once ( obj["харе"] = true
), then the second such assignment will not change anything.
The solution below creates an obj = {}
object and writes all the strings to it as property names. And then it collects the properties from the object into an array through for..in
. Duplicate will be gone.
01 |
function unique(arr) { |
06 |
obj[str] = true ; // запомнить строку в виде свойства объекта |
09 |
return Object.keys(obj); // или собрать ключи перебором для IE<9 |
12 |
var strings = [ "кришна" , "кришна" , "харе" , "харе" , |
13 |
"харе" , "харе" , "кришна" , "кришна" , "8-()" ]; |
15 |
alert( unique(strings) ); // кришна, харе, 8-() |
So you can put all the values as keys in the object, and then get it.
[Open task in new window]
split
method
The situation of real life. We are writing a message sending service and the visitor enters the names of those to whom to send it: Маша, Петя, Марина, Василий...
But it’s much more convenient for us to work with an array of names than with a single line.
Fortunately, there is a split(s)
method that allows you to turn a string into an array, breaking it up by separator s
. In the example below, the delimiter is a comma and a space.
1 |
var names = 'Маша, Петя, Марина, Василий' ; |
3 |
var arr = names.split( ', ' ); |
6 |
alert( 'Вам сообщение ' + arr[i]); |
The split
method has an optional second argument — a limit on the number of elements in the array. If there are more than specified, the remainder of the array will be discarded:
1 |
alert( "a,b,c,d" .split( ',' , 2 ) ); // a,b |
In practice, it is rarely used.
Calling str.split('')
will break the string into letters:
3 |
alert( str.split( '' ) ); // т,е,с,т |
join
method
Calling arr.join(str)
does exactly the opposite split
. It takes an array and sticks it together into a string, using str
as the delimiter.
For example:
1 |
var arr = [ 'Маша' , 'Петя' , 'Марина' , 'Василий' ]; |
3 |
var str = arr.join( ';' ); |
5 |
alert(str); // Маша;Петя;Марина;Василий |
Code to repeat the line 3
times:
1 |
alert( new Array(4).join( "ля" ) ); // ляляля |
As you can see, new Array(4)
makes an array without elements of length 4, which join
joins into a string, inserting the string "ля"
between its elements .
As a result, since the elements are empty, the string is repeated. Such a little trick.
Importance: 5
The solution is to turn obj.className
into an array using split
.
After that, you can check the presence of the class in it, and if not, add it.
01 |
function addClass(obj, cls) { |
02 |
var classes = obj.className ? obj.className.split( classes = obj.className ? obj.className.split( ' ' ) : []; |
05 |
if (classes[i] == cls) return ; // класс уже есть |
08 |
classes.push(cls); // добавить |
10 |
obj.className = classes.join( ' ' ); // и обновить свойство |
13 |
var obj = { className: 'open menu' }; |
15 |
addClass(obj, 'new' ); |
16 |
addClass(obj, 'open' ); |
18 |
alert(obj.className) // open menu new me |
PS An “alternative” approach to checking class presence by calling obj.className.indexOf(cls)
would be incorrect. In particular, it will find cls = "menu"
in the obj.className = "open mymenu"
class obj.className = "open mymenu"
.
PPS Check if your solution obj.className += " " + cls
assignment obj.className += " " + cls
. Does it not add an extra space if obj.className = ""
originally?
[Open task in new window]
Importance: 3
The problem can be solved in several ways. One of them is to break the string by the hyphen str.split('-')
, then successively construct a new one.
We split the string into an array, and then convert its elements and merge it back:
01 |
function camelize(str) { |
02 |
var arr = str.split( '-' ); |
05 |
// преобразовать: первый символ с большой буквы |
06 |
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); |
09 |
return arr.join( '' ); |
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone