desc: Значение по умолчанию в javascript
code: |
this.timeout = p.timeout || 5000
desc: |
Добавить к html элементу событие, так что оно
будет выполняться в пространстве этого элемента
code: |
<a href='#' onclick='return js_link.call(this)'>link</a>
desc: Итерация по объектам
code: |
for (var k in window.document)
document.write(k + " - " + window.document[k] + "<br>")
code: |
var a = [function(sep){
return 'a_b_c'.split(sep);
}];
a[0]('_')[0];
desc: Перенаправить пользователя на другую страницу
code: |
window.location = 'http://ya.ru'
desc: Перезагрузить страницу
code: |
window.location.reload()
desc: Спрашиваем бразуер о местоположении
code: |
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(fsbkgb) {
var pod_kolpakom = true;
});
}
desc: Открыть из javascript ссылку в новом окне
code: |
window.open('http://www.mydomain.com?ReportID=1');
desc: Получить элемент по id
code: |
function byid(id){
return document.getElementById(id);
}
desc: Удалить элемент из массива
link: http://stackoverflow.com/questions/4825812/clean-way-to-remove-element-from-javascript-array-with-jquery-coffeescript
code: |
Array.prototype.remove = function(e) {
var t, _ref;
if ((t = this.indexOf(e)) > -1) {
return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
}
};
var arr = [1,2,3,4,3]
arr.remove(3)
console.log(arr)
out: |
[1,2,4,3]
desc: |
Сериализовать объект в JSON и обратно.
data:
-
code: |
JSON.stringify({foo: 'bar'})
out: |
'{"foo":"bar"}'
-
code: |
JSON.parse('{"foo":"bar"}')
out: |
{ foo: 'bar' }
link: http://javascript.ru/basic/regular-expression
desc: Есть 2 способа записи регулярных выражений
code: |
var reg = /ab+c/i
var reg = new RegExp("ab+c", "i")
link: http://javascript.ru/basic/regular-expression
desc: Сопоставить строку с регулярным выражением
code: |
if(/\s/.test("строка")){
// В строке есть пробелы!
}
link: http://www.w3schools.com/jsref/jsref_replace.asp
desc: Заменить все вхождения подстроки в строке, без учёта регистра
code: |
var str="Welcome to Microsoft! ";
str = str + "We are proud to announce that Microsoft has ";
str = str + "one of the largest Web Developers sites in the world.";
document.write(str.replace(/microsoft/gi, "W3Schools"));
out: |
Welcome to W3Schools! We are proud to announce that W3Schools
has one of the largest Web Developers sites in the world.
link: http://habrahabr.ru/blogs/javascript/117868/
ft: javascript
desc: Получить колличество аргументов, которые объявлены в описании функции
code: |
function one (foo) {};
function three (foo, bar, qux) {};
console.log( one.length); // 1
console.log(three.length); // 3
desc: Парсинг URL хэша
code: |
// Задача, разобрать URL вида:
// domain.com/#user/videos/18?view=fullscreen&quality=1080
function parseUrl() {
// Получаем кусок пути, после #
var url = document.location.hash.replace('#',''),
// Получаем путь
path = url.split('?')[0].split('/'),
// Получаем массив пар 'key=value'
pairs = url.split('?')[1] ? url.split('?')[1].split('&') : false,
params = {},
i;
// собираем пары ключ значение в обьект.
if (pairs) {
for(i in pairs) {
pairs[i] = pairs[i].split('=');
params[pairs[i][0]] = pairs[i][1];
}
}
// Возвращаем обьект, содержащий всю инфу об URL
return {
path : path,
params : params
}
}
console.log(parseUrl().path); // ['user','videos','18'];
console.log(parseUrl().params); // { view : 'fullscreen', quality : 1080 }
desc: Компиляция URL из обьекта
code: |
function compileUrl(url) {
var string = '#',
pairs = [],
i;
string += url.path.join('/');
for(i in url.params) pairs.push([i,url.params[i]].join('='));
if (pairs.length) string += '?'+pairs.join('&');
return string;
}
compuleURL({
path : ['user','videos','18'],
params : {
quality : 480
}
});
// Возвращает '#user/videos/18?quality=480'